@Mock Injection @InjectMocks in Spring Boot + Mockito + JUnit fails

Problem Description

The test code is as follows:

@RunWith(SpringRunner.class)
@SpringBootTest
public class CheckConfirmPayServiceTest {

    private static final Logger logger = LoggerFactory.getLogger(CheckConfirmPayServiceTest.class);

    @Mock
    private CashierService cashierService;

    @Autowired
    @InjectMocks // The class injected into the mock object is generally the class being tested
    private CheckConfirmPayService checkConfirmPayService;

    @Autowired
    private TScanStatementJobMapper tScanStatementJobMapper;


    private String jobFlowNo = FlowNoUtil.getTxNo();

    private String sysOrderNo = "S" + FlowNoUtil.getTxNo();

    @Before
    public void setUp() throws Exception {
        // Mock
        MockitoAnnotations.initMocks(this);
        Mockito.doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                CashierCheckConfirmPayRequest request = (CashierCheckConfirmPayRequest) args[0];
                logger.info("===== Mock interface test =" = ");
                CashierCheckConfirmPayResponse response = new CashierCheckConfirmPayResponse();
                if (request == null) {
                    throw new BizException(ErrorCodeEnum.NULL_POINTER_EXCEPTION.code,
                            ErrorCodeEnum.NULL_POINTER_EXCEPTION.msg);
                }
                response.setReqsysNo(request.getReqsysNo());
                response.setVersion(request.getVersion());
                return response;
            }
        }).when(cashierService).checkConfirmPay(Mockito.any(CashierCheckConfirmPayRequest.class));
        insertTScanStatementJob();
    }

    /**
           * Insert reconciliation status data
     *
     * @author shenhaiwen
     * @time  August 27, 2018, 2:12:31 PM
     */
    private void insertTScanStatementJob() {
        String checkDate = TimeUtil.addDays(-1); // the day before the current date
        TScanStatementJob job = new TScanStatementJob();
        job.setJobFlowNo(jobFlowNo);
        job.setCheckDate(checkDate);
        job.setStatementFlag(StatementFlagEnum.FINISH.getCode());
        job.setCreateTime(TimeUtil.getTimeStamp());
        job.setUpdateTime(TimeUtil.getTimeStamp());
        job.setRemark("Unit Test Data");
        tScanStatementJobMapper.insert(job);
    }

    @After
    public void delData() {
        tScanStatementJobMapper.deleteByPrimaryKey(jobFlowNo);
    }

    /**
           * Batch processing to confirm payment scenarios
     *
     * @author shenhaiwen
     * @time  August 4, 2018, 11:26:16 AM
     */
    @Test
    public void testRemoteCheckConfirmPay() {
        CallBackStatusEnum callBackStatusEnum = null;
        try {
            callBackStatusEnum = checkConfirmPayService.remoteCheckConfirmPay();
        } catch (Exception e) {
            TestCase.fail();
        }
        TestCase.assertEquals(CallBackStatusEnum.SUCCESS.getStatus(), callBackStatusEnum.getStatus());

    }

In the test class, mock the CashierService object and inject it into checkConfirmPayService, and then execute the CashierService method in the test method.

But now the problem is that the cashierService attribute of checkConfirmPayService is not injected by the @Mock tag, but the @Autowired tag is called, using the bean generated by spring instead of the cashierService of the mock.

The results are as follows:

problem causes

The current version only supports setter injection. Mockito first attempts type injection. If there are multiple mock objects of the same type, it will be injected based on the name. Mockito will not throw any exception when the injection fails, so you may need to manually verify its security.

Therefore, the cashierService needs to be injected in checkConfirmPayService using setter. The sample code is as follows:

@Before
    public void setUp() throws Exception {
        // Mock
        MockitoAnnotations.initMocks(this);
        checkConfirmPayService.setCashierService(cashierService);
        ............

The test entered the cashierService's mock as expected, as follows:

Intelligent Recommendation

Mock InjectMocks (@Mock and @InjectMocks) difference

@Mock: Create a Mock. @InjectMocks: create an instance, mock rest with @Mock (or @Spy) annotations created will be injected with this example. SomeHandler @Autowired class objects OneDependency class,...

Summary of the use of@SPY,@Mock, and @Injectmocks in the Springboot Junit 5

Summary of the use of@SPY,@Mock, and @Injectmocks in the Springboot Junit 5 Actual combat code github addresshttps://github.com/wand007/cloud-example/blob/master/example-jpa/example-client/src/test/ja...

Mockito and Spring Mock in Java

Foreword When self-test in development, the interface is often required to open with other classmates, sometimes there is no data without the pick, you can only pay attention to your code. Mockito ret...

Junit, AssertJ, Hamcrest, Mockito, PowerMock, spring boot test

Source code github:https://github.com/lotusfan/junit-demo Test directory JUnit The JUnit 5 runtime is a Java 8 environment. JUnit4 and JUnit 5 common annotations JUnit4 Junit5 Description @Test @Test ...

The difference between Mock and InjectMocks

Interview: Do you know what is a distributed system? Does the Redis distributed lock? >>>   If it is the above way, then The code in the red box method will not be executed, this se...

More Recommendation

Spring boot integration mockito

spring boot mockito integration and consolidation mockito spring is the same, no difference The introduction of a dependent:   Entity classes: dao:    service   In the test directo...

Spring Boot unit testing using mock out the entire frame mockito Redis

Outline When we use unit tests to verify the application code, if the code is required to accessRedis, Then in order to ensure the unit does not depend on the testRedis, Requires that the entireRedis ...

Android best Mock unit test solution: JUnit + Mockito + Powermock

This article aims to guide developers to Mock unit testing in Android projects. What is unit testing A unit test consists of a set of independent tests, each for a single program unit in the software....

Mockito configures a mock object in the Spring container

Mockito configures a mock object in the Spring container In the unit test, some bean relies when the initialized Spring container relies...

Use Spring+Junit+Mockito for code self-test

When refactoring the code, a complete set of testing work can give us a great help. Below I use the Demo made by Mockito to replace the relevant interface of Dubbo. For reference for students who are ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top