Path to continuous integration-test failure caused by mock object

Source: Internet
Author: User

Today I encountered a very strange problem and had a long struggle. When talking to colleagues about this problem, I suddenly thought of the problem.

Symptom:There are eight test cases in the unit test class of a service, which can pass normally during separate operation. However, when running together, there will always be two fixed test failures.

Cause:One test case mock is a DaO object on which the service depends. When the subsequent use case uses this Dao object again, mock is used instead of the Instance initialized by spring.

Solution:At the end of the test case, set the DaO object initialized by spring to the service object. The Code is as follows:

Public class reportservicetest {// tested service, initialized by spring @ autowired private userservice; // Dao dependent on service, initialized by spring @ autowired private userdao; @ test @ databasesetup ("dataset. XML ") // test the dataset public void testgetmanager () {// create the mock object userdao mockuserdao = mock (userdao. class); // set the mock Dao to simulate the action when (...). thenreturn (..); // Replace the dependency (userserviceimpl) userservice ). setuserdao (mockuserdao );/ /Specific test code ...... // Replace the mock Dao (userserviceimpl) userservice). setuserdao (userdao );}}

In addition to the above method, you can also solve the above problem by setting the execution sequence of the case. However, this method is risky. Make sure that the test cases of the mock object are executed at the end, and the execution sequence must be arranged between all the use cases of the mock object. For how to specify the execution sequence of test cases, refer to the following article:

Understanding JUnit method order executionJUnit test method orderingOrdered testcases execution in junit 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.