The above example is an idealized state, but in real-world development, we need to call some functions that depend on a particular environment or code that is written by a colleague, and colleagues only provide interfaces. This time we need to use Mockito to help us complete the test.
Of course, you can choose Easymock, Jmock and other mock tools
Here is a direct reference to the example in the Powermock manual
class to be tested:
Public class EmployeeService { private EmployeeDAO EmployeeDAO; Public EmployeeService (EmployeeDAO employeedao) { this. EmployeeDAO = EmployeeDAO; }}
Methods to be tested for class invocation
Public class EmployeeDAO { publicint gettotal () { thrownew Unsupportedoperationexception (); }}
One of the gettotal is a function that cannot be tested using normal methods.
Test class:
Public classemployeeservicetest {@MockPrivateEmployeeDAO EmployeeDAO; EmployeeService EmployeeService; @BeforeMethod Public voidinit () {mockitoannotations.initmocks ( This); EmployeeService=NewEmployeeService (EmployeeDAO); } @Test Public voidTestgettotalemployee () {Powermockito.when (Employeedao.gettotal ()). Thenreturn (10); intTotal =Employeeservice.gettotalemployee (); Assertequals (10, total); }}
@Mock is the Mockito tag used with mockitoannotations.initmocks (this), which is equivalent to
EmployeeDAO EmployeeDAO = Mockito.mock (Employeedao.class)
If some objects are used repeatedly in the test class, the previous one can save a lot of code.
@BeforeMethod is a testng tag that runs this method before running a very test method
@Test testng identification, indicating that this method is a test method
Powermockito.when (Employeedao.gettotal ()). Thenreturn (10);
Record the behavior of the mock, returning 10 when calling the Gettotal method
For details, please refer to: http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html
Here is the result of the operation:
[TestNG] running:c:\users\changzhz\appdata\local\temp\testng-eclipse--599967477\testng-Customsuite.xmlPASSED:testGetTotalEmployee===============================================Default Test Tests run:1, failures:0, skips:0========================================================================================== ====Default suitetotal tests run:1, failures:0, skips:0===============================================[TestNG] time taken by [email protected]:49ms[testng] Time taken by [email protected]:8ms[testng] Time taken by [email protected]:37ms[testng] Time taken by [Failedreporter passed=0 failed=0 Skipped=0]: 1ms[testng] Time taken by [email protected]:3ms[testng] Time taken by [email protected]:5 ms
A class or interface that cannot be invoked in a development environment with a mockito mock