With PowerMock, you can make it return an arbitrary object when instantiated, or return an exception.
It is assumed that the constructor of the Utility class (mocking class) called from the UseUtility class (test target class) is mocked.
This is the class to be tested that is called from JUnit.
I have instantiated the Utility class in the method, and I want to set the objects and exceptions returned at this time to arbitrary ones.
UseUtility.java
public class UseUtility {
public void createUtility() throws Exception {
Utility utility = new Utility();
//Omitted thereafter
}
}
Mock it and define arbitrary behavior in the constructor.
Utility.java
public class Utility {
public Utility() throws Exception {
//abridgement
}
}
JUnit that calls the class under test.
To use PowerMock with JUnit, specify PowerMockRunner for @RunWith
.
Note that in @PrepareForTest
, not only the class to be mocked, but also the class that calls the constructor must be written.
UseUtilityTest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Utility.class, UseUtility.class })
public class UseUtilityTest {
//abridgement
}
thenReturn Set the instance returned by the constructor of the mocked class.
The mock is set to be returned here, but it does not have to be a mock.
@Test
public void test_thenReturn() throws Exception {
//Preparation
//Mocking
Utility mock = PowerMockito.mock(Utility.class);
//Set the instance to be returned in the constructor
PowerMockito.whenNew(Utility.class).withNoArguments().thenReturn(mock);
//Run
UseUtility obj = new UseUtility();
obj.createUtility();
}
thenThrow Set an exception that occurs in the constructor of the mocked class.
@Test(expected = Exception.class)
public void test_thenThrow() throws Exception {
//Preparation
Exception exception = new Exception("error!");
//Mocking
PowerMockito.mock(Utility.class);
//Set exceptions that occur in the constructor
PowerMockito.whenNew(Utility.class).withNoArguments().thenThrow(exception);
//Run
UseUtility obj = new UseUtility();
obj.createUtility();
}
PowerMock provides verifyNew for validating mocked constructors.
You can use Mockito's times, atLeast, asLeastOnce, etc. to verify the number of calls.
verifyNew (Utility.class) is synonymous with verifyNew (Utility.class, times (1)).
//Confirm that it was called once
PowerMockito.verifyNew(Utility.class).withNoArguments();
Recommended Posts