I'm writing java unit test for a legacy code and I'm new to this area as well. I have to test following scenario (write unit test case for the testableMethod()
). So, without executing code inside the getMode()
method, I want to get a value for the mode
variable.
Class A{
public boolean testableMethod()
{
//code
......
int mode = getMode();
......
//do something with mode
return X;
}
private int getMode()
{
return ComplexCalls(ComplexMethodCalls(), more());
}
}
I've tried to do it using PowerMockito without getting success. It is possible to mock these kind of scenario with PowerMockito?.
You can with a PowerMockito
spy:
public class A {
public boolean testableMethod() {
return getMode() == 1;
}
private int getMode() {
return 5;
}
}
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.spy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class ATest {
@Test
public void testableMethod_should_do_this() throws Exception {
A a = spy(new A());
doReturn(1).when(a, "getMode");
assertTrue(a.testableMethod());
}
}
See all this full example of partial mocking of a private method
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments