天天看點

springboot單元測試mock依賴的類

引入包,測試版本:<powermock.version>1.7.1</powermock.version>

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
           
//aService類的findStudyInfoById方法内部實作,調用了bDao的方法,
//單元測試隻需關心aService目前層的正确性,bDao的正确性由它自己的單元測試保證,
//是以需要模拟一個假的bDao場景,來配合完成aService的單元測試
public class MockTest {
 
    //注入要測試類,注意這裡注入寫實作類,不能寫接口注入
    @InjectMocks
    private AServiceImpl aService;
 
    //mock這個類,幫助測試aService,而不測試實際的bDao
    @Mock
    private BDao bDao;
 
    //初始化測試資料
    @Before
    public void initMock() {
        MockitoAnnotations.initMocks(this);
        Student student = new Student;
        student.setName("測試");
        student.setId(1);
        //初始化mock類的場景,如果傳入一個int,傳回自己mock的student資料
        when(bDao.findStudyInfoById(anyInt())).thenReturn(student);
    }
 
    @Test
    public void findStudyInfoById() throws Exception {
        List<Student> students = aService.findStudyInfoById(1);
        Assert.assertTrue(rstudents.size()==1);
    }
 
}
           

繼續閱讀