gpt4 book ai didi

java - JSF 支持 Bean 单元测试

转载 作者:搜寻专家 更新时间:2023-11-01 03:54:47 26 4
gpt4 key购买 nike

我有一个名为 e.g. 的支持 bean PeopleListBean。目的很简单:从存储库返回人员列表。

public class PeopleListBean {

@Autowired
private PersonRepository personRepository;

private List<Person> people;

@PostConstruct
private void initializeBean() {
this.people = loadPeople();
}

public List<User> getPeople() {
return this.people;
}

private List<Person> loadPeople() {
return personRepository.getPeople();
}

}

我想使用 Junit 和 Mockito 为这个 bean 创建一个单元测试。
下面的示例测试类:

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.example.PersonRepository;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/test-application-context.xml" })
public class PeopleListBeanTest {

@Autowired
private PeopleListBean peopleListBean;
@Autowired
private PersonRepository mockPersonRepository;

@Before
public void init() {
reset(mockPersonRepository);
}

@Test
public void canListPeople() {
List<Person> people = getDummyList();

when(mockPersonRepository.getPeople().thenReturn(people);

assertTrue(peopleListBean.getPeople().size() == people.size());
}
}

我的问题是,何时/如何模拟存储库,因为加载发生在 initializeBean 方法 (@PostConstruct) 中。因此,在构造类之后,在我可以实际模拟导致断言不匹配的方法之前调用“getPeople”方法。

我非常感谢一些帮助/指导!

最佳答案

使用 JUnit 的 @BeforeClass注释

因此您的代码将如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/test-application-context.xml" })
public class PeopleListBeanTest {

@Autowired
private PeopleListBean peopleListBean;
@Autowired
private PersonRepository mockPersonRepository;

@BeforeClass
public static void initialise() {

}

// .
// .
// .
}

关于java - JSF 支持 Bean 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com