用Mockito mock普通的方法


上面的例子是很理想化的狀態,但是在實際的開發中,我們需要經常調用一些依賴特定環境的函數或者調用同事寫的代碼,而同事僅提供了接口。這個時候就需要利用Mockito來協助我們完成測試。

當然,你可以選擇easyMock ,jmock等mock工具

在這里直接引用《PowerMock實戰手冊》中的例子

待測類:

public class EmployeeService {
    private EmployeeDao employeeDao;

    public EmployeeService(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }
}

待測類調用的方法

public class EmployeeDao {
    public int getTotal() {
        throw new UnsupportedOperationException();
    }
}

其中 getTotal 就是一個利用正常辦法無法測試的函數。

測試類:

public class EmployeeServiceTest  {
    @Mock
    private EmployeeDao employeeDao;
    EmployeeService employeeService;


    @BeforeMethod
    public void init(){
         MockitoAnnotations.initMocks(this);
         employeeService = new EmployeeService(employeeDao);
    }
    

    @Test
    public void testGetTotalEmployee() {
        PowerMockito.when(employeeDao.getTotal()).thenReturn(10);
        int total = employeeService.getTotalEmployee();
        assertEquals(10, total);
    }
}

@Mock 是Mockito的標記 與MockitoAnnotations.initMocks(this) 配合使用,等效於

EmployeeDao employeeDao = Mockito.mock(EmployeeDao.class)

如果些對象在測試類反復使用的話,前一種寫法能節省很多代碼

@BeforeMethod 是testNG標記 ,作用是在運行很一個測試方法之前運行此方法

@Test testNG標識,表明此方法是一個測試方法

PowerMockito.when(employeeDao.getTotal()).thenReturn(10);
錄制mock的行為,當調用getTotal方法時,返回10
具體請參照:http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html

下面是運行結果:

 
        
[TestNG] Running:
  C:\Users\changzhz\AppData\Local\Temp\testng-eclipse--599967477\testng-customsuite.xml

PASSED: testGetTotalEmployee

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@5f205aa: 49 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@424c0bc4: 8 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@2ff5659e: 37 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 1 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1996cd68: 3 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@27ddd392: 5 ms

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM