Today I met a very strange problem, tangled for a long time. When I was talking to colleagues about this problem, I suddenly thought of the problem.
problem: There are eight test cases in the Unit test class of a service that can be passed normally when run separately. But once run together, there will always be a fixed two test failures.
problem Reason: There is a test case that mocks a DAO object that the service relies on, and then uses the mock instead of the instance of spring initialization when using the DAO object.
Workaround: at the end of the test case, re-initialize the DAO object set to the service object with spring, specific code:
public class Reportservicetest {
//tested service, initialized by spring
@Autowired
private userservice userservice;
Service-dependent DAO, initialized by spring
@Autowired
private Userdao Userdao;
@Test
@DatabaseSetup ("dataset.xml")//test DataSet public
void Testgetmanager () {
//Create mock object
Userdao Mockuserdao = mock (userdao.class);
Set the action that the mock DAO will simulate when
(...). Thenreturn (..);
Substitution Dependencies (
(Userserviceimpl) userservice). Setuserdao (Mockuserdao);
Specific test code ...
Replace the mock Dao (
(Userserviceimpl) userservice). Setuserdao (Userdao);
}
In addition to the above methods, you can also solve the above problems by setting the execution order of the use cases. However, this approach is still risky, and it is important to ensure that test cases that use mock objects are executed at the end, and that the execution order is arranged between all use cases using mock objects. For information on how to specify the order in which test cases are executed, refer to the following article:
Understanding JUnit Method Order Execution
junit test-ordering
Ordered testcases execution in June It 4