[英]Using Mockito on one test method making other Test methods fail
我正在为我正在测试的服务 class 创建集成测试,我需要为其中一种测试方法模拟 dao。 问题是当我一起运行测试时,我的一些测试失败了,但是当我单独运行它们时,测试过去了。 如果我删除 mockito 部分,当我一次运行它们时,我的所有测试都会通过。 对此的任何见解表示赞赏
下面是我的代码:
// here is my Service class
public class Service {
Dao dao;
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
}
//here is my integ test
@Category(IntegrationTest.class)
@RunWith(SpringRunner.class)
public class Test{
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
@Qualifier(Service.SERVICE_NAME)
protected Service service;
@Before
public void setUp() {
assertNotNull(service);
}
@Test
public void testDoSomethingOne() throws Exception {
Dao dao = Mockito(Dao.class)
service.setDao(dao)
boolean flag = service.doSomething();
Assert.assertTrue(flag);
}
@Test
public void testDoSomethingTwo() throws Exception {
Integer num = service.doSomething();
Assert.assertNotNull(num);
}
测试方法testDoSomethingOne()
为它为测试的 rest 保留的服务实例设置模拟 dao。
使用 @DirtiesContext 注释方法testDoSomethingOne testDoSomethingOne()
以获取与后续测试方法关联的新上下文。
测试注释,指示与测试关联的 ApplicationContext 是脏的,因此应该关闭并从上下文缓存中删除。
如果测试修改了上下文,则使用此注释 - 例如,通过修改 singleton bean 的 state,修改 state bean,修改 state 将提供相同上下文的新上下文的测试,等等。
您可以在每次测试之前获取 dao 并在测试后将其分配回服务,如下所示:
private static Dao dao;
@Before
public void setUp() {
if(dao == null) {
dao = service.getDao();
}
}
@After
public void tearDown() {
service.setDao(dao);
}
如果是集成测试,您不应该模拟您的 daos,推荐的方法是使用 memory 数据库中的 a ,例如H2
。 spring 人员已经提供了注释@DataJpaTest
,它可以为您创建数据库。
You can use the @DataJpaTest annotation to test JPA applications. By default, it scans for @Entity classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. Regular @Component beans are not loaded into the ApplicationContext.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.