接着上一篇文章中的代碼,修改下service中的代碼,此次我不經過構造器注入Dao,在方法中new一個StudentDao,建立一個名爲StudentNewService的類。api
具體示例代碼以下:單元測試
package com.rongrong.powermock.service; import com.rongrong.powermock.dao.StudentDao; /** * @author rongrong * @version 1.0 * @date 2019/11/17 21:13 */ public class StudentNewService { /** * 獲取學生個數 * @return返回學生總數 */ public int getTotal() { StudentDao studentDao = new StudentDao(); return studentDao.getTotal(); } /** * 建立學生 * @param student */ public void createStudent(Student student) { StudentDao studentDao = new StudentDao(); studentDao.createStudent(student); } }
針對上面修改部分代碼,進行單元測試,如下代碼有采用傳統方式測試和採用powermock方式進行測試,具體代碼以下:測試
package com.rongrong.powermock.service; import com.rongrong.powermock.dao.StudentDao; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * @author rongrong * @version 1.0 * @date 2019/11/20 21:42 */ @RunWith(PowerMockRunner.class) @PrepareForTest(StudentNewService.class) public class TestNewStudentService { /** * 傳統方式測試 */ @Test public void testGetStudentTotal() { StudentNewService studentNewService = new StudentNewService(); int total = studentNewService.getTotal(); assertEquals(total, 10); } /** * @desc測試有返回值類型 採用powermock進行測試獲取學生個數 */ @Test public void testGetStudentTotalWithPowerMock() { //先模擬一個假對象即studentdao方法中的局部變量 StudentDao studentDao = PowerMockito.mock(StudentDao.class); try { //這句話我按照英文理解就是,我用無參的方式new了一個StudentDao對象 PowerMockito.whenNew(StudentDao.class).withNoArguments().thenReturn(studentDao); //再模擬這個對象被調用時,咱們默認假定返回10個證實調用成功 PowerMockito.when(studentDao.getTotal()).thenReturn(10); //這裏就是service就不用再說了 StudentNewService studentNewService = new StudentNewService(); int total = studentNewService.getTotal(); assertEquals(total, 10); } catch (Exception e) { fail("測試失敗了!!!"); e.printStackTrace(); } } /** * @desc測試的無返回值類型 採用powermock進行測試建立學生 */ @Test public void testCreateStudentWithPowerMock() { //先模擬一個假對象即studentdao方法中的局部變量 StudentDao studentDao = PowerMockito.mock(StudentDao.class); try { //這句話我按照英文理解就是,我用無參的方式new了一個StudentDao對象 PowerMockito.whenNew(StudentDao.class).withNoArguments().thenReturn(studentDao); Student student = new Student(); //這句話註釋與否都能運行經過,也就是我只能判斷他是否被調用 //PowerMockito.doNothing().when(studentDao).createStudent(student); //這裏就是service就不用再說了 StudentNewService studentNewService = new StudentNewService(); studentNewService.createStudent(student); Mockito.verify(studentDao).createStudent(student); } catch (Exception e) { fail("測試失敗了!!!"); e.printStackTrace(); } } }
運行上面的測試用例,會發現第一個失敗,後面兩個都運行成功,即有返回值和無返回值類型的測試(void類型)。spa
注意:對於無返回值類型的測試,只能驗證其是否被調用,這裏還請注意。code