在一种测试方法上使用Mockito会使其他测试方法失败



我正在为正在测试的服务类创建集成测试,我需要为其中一个测试方法模拟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()为服务实例设置mock dao,并为其余测试保留该mock dao。

用@DirtiesContext注释方法testDoSomethingOne(),以获得与后续测试方法关联的新上下文。

测试注释,指示关联的ApplicationContext测试是脏的,因此应该关闭并从上下文缓存。

如果测试修改了context——例如通过修改singleton bean的状态,修改嵌入式数据库的状态等。后续测试则相同上下文的请求将被提供一个新上下文。

您可以在每次测试前获取dao,并在测试后将其分配回服务像这样的东西:

private static Dao dao;
@Before
public void setUp() {
if(dao == null) {
dao = service.getDao();
}
}
@After
public void tearDown() {
service.setDao(dao);
}

如果这是一个集成测试,您不应该模拟您的dao,建议使用像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.

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-功能测试spring引导应用程序测试自动配置的jpa测试

最新更新