Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Mock static non-void private methods

In this post, I am going to explain how to mock Static non-void private methods.

Following snippet is used to mock the static non-void private method ‘readInputFromUI’.

String message = "Enter a number";
String methodToMock = "readInputFromUI";

PowerMock.mockStaticPartial(InputUtil.class, methodToMock);

PowerMock.expectPrivate(InputUtil.class, methodToMock, message).andReturn(10).times(1);

Following is the complete working application.

InputUtil.java
package com.sample.tests;

import javax.swing.JOptionPane;

public class InputUtil {

public static int readInput(String message){
return readInputFromUI(message);
}

private static int readInputFromUI(String message){
int number = Integer.parseInt(JOptionPane.showInputDialog(message));
return number;
}

}


InputUtilTest.java
package com.sample.tests;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ InputUtil.class })
public class InputUtilTest {

@Test
public void mockVoidEvenMethod() throws Exception {
String message = "Enter a number";
String methodToMock = "readInputFromUI";

PowerMock.mockStaticPartial(InputUtil.class, methodToMock);

PowerMock.expectPrivate(InputUtil.class, methodToMock, message).andReturn(10).times(1);

PowerMock.replayAll();

int number = InputUtil.readInput(message);

assertEquals(number, 10);
PowerMock.verifyAll();

}
}




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Mock static non-void private methods

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×