- Simulating local variables Mock the local Variable
There is a simulation that returns worthwhile local variables!
The local variables here do not take the method of dependency injection, but instead of a method inside the new EmployeeDAO, we usually write such code, we can often or encounter such a problem, then we how to solve the problem!
publicclass EmployeeService {publicintgetTotalEmployee(){ new EmployeeDao(); return employeeDao.getTotal();}}
Note: When using the Powermockito.whennew method, annotations @preparefortest and @runwith must be added. The class written in note @preparefortest is the class where the new object code that needs the mock is located.
Gettotalemployee () because the test is not able to modify the method, no matter what is inside, local variables we can not touch, so! Intelligent simulation, can not be changed, this correction is likely to cause system defects. If you don't pay attention, you're done. Very need to be careful as a tester!/** * Tested with Powermock * *@Test Public void Testgettotalemployeewithmock() {EmployeeDAO EmployeeDAO = Powermockito.mock (Employeedao.class);Try{powermockito.whennew (Employeedao.class). Withnoarguments ()//Not enough parameters to build! Returns the simulated local variables! . Thenreturn (EmployeeDAO); Powermockito.when (Employeedao.gettotal ()). Thenreturn (Ten); EmployeeService Service =NewEmployeeService ();intTotal = Service.gettotalemployee (); Assertequals (Ten, total); }Catch(Exception e) {Fail ("The test failed."); } }}
While the Mock test is successful, of course you might be surprised Powermock altogether has such a powerful ability to
Mock out local variables.
* Void method for local variables
How to test it?
publicvoidcreateEmployeenew EmployeeDao();employeeDao.addEmployee(employee);}
@TestpublicvoidtestCreateEmployeeWithMock() { EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class); try { PowerMockito.whenNew(EmployeeDao.class).withNoArguments() .thenReturn(employeeDao); new Employee(); new EmployeeService(); service.createEmployee(employee); Mockito.verify(employeeDao).addEmployee(employee); catch (Exception e) { fail(); }
To test the method of void return type, the same thing we do is to judge whether he is called
public Class Classdependency {public static Boolean isexist () {//do nothing return false ; } }
Trial example code: @RunWith ( Powermockrunner.class) public class testclassundertest { @Test @PrepareForTest ( Classdependency.class) public void testcallstaticmethod () {classundertest undertest = new Clas Sundertest (); Powermockito.mockstatic (Classdependency.class); Powermockito.when (Classdependency.isexist ()). Thenreturn (true ); Assert.asserttrue (Undertest.callstaticmethod ()); }}
Verifying
Verifying is a very powerful test tool that is used not only in Powermock, but also in frameworks like Easymock,mockito, whose purpose is to check that a test method has been successfully invoked.
Advanced Study of Powermock