單元測試Service使用mockito

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;


  1. maven中添加

<!-- mockito -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>
        <!-- junit 4 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>

2.要調用的service用@InjectMocks註解,service裏面用@Mock註解

    @InjectMocks
    @Autowired
    private TestService testService;

    @Mock
    private TestMapper testMapper;

3.用@Before初始化mock
     @Before
    public void init() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

4.模擬數據


        when(testMapper.getTestList()).thenReturn(list1);

        List<TestInfo> list = testService.getTestList();
        assertEquals("bname", list.get(0).getTest_name());


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章