Continuous integration path The test failure caused by the--mock object

Source: Internet
Author: User

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



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.