AdSense

網頁

2020/4/10

Spring Boot 2.1.x JUnit 4 @MockBean example

Spring Boot 2.1.x 使用JUnit 4及@MockBean做stubbing測試類簡單範例。

本範例只是要強調Spring Boot 2.1.x的JUnit 4測試類中如果要使用@MockBean注入mock物件,則類別前要掛上@RunWith(SpringRunner.class),否則會是null導致呼叫時NullPointerException發生。

DemoTest

package com.abc.demo.service;

import com.abc.demo.dao.DemoDao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

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

    @MockBean
    private DemoDao dao;

    @Autowired
    private DemoService service;

    @Test
    public void doDemoTest() {

        int value1 = 1;
        int value2 = 2;
        int modelValue = 2

        Mockito.when(dao.getModel(value1, value2).thenReturn(modelValue);

        boolean actual = service.doDemo(value1, value2);
        Assert.assertTrue(actual);

    }
}

參考:

沒有留言:

AdSense