The Mock system class

Note: Although all the examples shown here are made using the EasyMock API extension, the same techniques apply to the Mocktio API extension.

The overview

  1. Use on a class@RunWith(PowerMockRunner.class)Annotation.
  2. Use on a class@PrepareForTest({ClassThatCallsTheSystemClass.class})Annotation.
  3. usemockStatic(SystemClass.class)Mock the system class and set the normal expected value.
  4. Only EasyMock is available: usePowerMock.replayAll()Switch to replay mode.
  5. Only EasyMock is available: usePowerMock.verifyAll()Switch to Verify mode.

The sample

PowerMock 1.2.5 and later support methods in Mock Java system classes, such as those found in java.lang and java.net. This method does not require modifying JVM or IDE Settings! These classes are simulated in a slightly different way than usual. Normally, you would prepare a class containing static methods to emulate (let’s call it X), but because PowerMock can’t prepare the system classes to test, you have to take a different approach. So instead of preparing X, prepare classes that call static methods in X! Let’s look at a simple example:

public class SystemClassUser {

	public String performEncode(a) throws UnsupportedEncodingException {
		return URLEncoder.encode("string"."enc"); }}Copy the code

Here we simulate java.net.URLEncoder#encode(..) for static method calls that are not normally possible. Methods. Since the URLEncoder class is a system class, we should prepare SystemClassUser for testing, since it is the class that calls the Encode method in URLEncoder. Such as:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SystemClassUser.class})
public class SystemClassUserTest {

	@Test
	public void assertThatMockingOfNonFinalSystemClassesWorks(a) throws Exception {
		mockStatic(URLEncoder.class);

		expect(URLEncoder.encode("string"."enc")).andReturn("something");
		replayAll();

		assertEquals("something".newSystemClassUser().performEncode()); verifyAll(); }}Copy the code