PowerMockito private void method issue - java

I have below class
class PowerMockitoTest{
private void TestPrivateMethod(){
System.out.println("Inside private method");
}
public void TestPublicMethod(){
System.out.println("Inside public method");
TestPrivateMethod();
}
}
I have created Test class as below
#RunWith(PowerMockRunner.class)
public class PowerMockitoExampleTest {
#Test
public void test() throws Exception {
PowerMockitoTest testclass = PowerMockito.spy(new PowerMockitoTest());
PowerMockito.doNothing().when(testclass,"TestPrivateMethod");
testclass.TestPublicMethod();
}
}
Instead of getting OP as 'Inside public method' I am getting very strange OP as 'Inside private method'. Though i have stubbed private method to do nothing its getting called as well as sysout for public method is not getting printed.
Its working fine when i used PowerMockito.doAnswer() but it requires method to be at package level instead of private.

Write it this way:
PowerMockitoTest testclass = PowerMockito.spy(new PowerMockitoTest());
try {
PowerMockito.doNothing().when(testclass, PowerMockito.method(PowerMockitoTest.class, "TestPrivateMethod")).withNoArguments();
} catch (Exception e) {
e.printStackTrace();
}
testclass.TestPublicMethod();
btw:
Testing is about mocking input and investigating outputs (it can be state of module, result of function or calls to another functions).
You should not mock private methods, as their result should not be treated as an input becouse they are not visible from outside.

The missing part in your code i believe is the #PrepareForTest part. You have to add class name with #PrepareForTest after #RunWith annotation
#RunWith(PowerMockRunner.class)
#PrepareForTest({Class1.class, Class2.class})
public class ClassTest

Related

MockitoException when trying to mock java.lang.System

I have a test case that mock a static method of java.lang.System class:
#Test
fun `getLocalTime()`() {
// Arrange
val staticMock = Mockito.mockStatic(System::class.java)
Mockito.`when`(System.currentTimeMillis()).thenReturn(1000L)
// Action
val res = deviceTimeProvider.getLocalTime()
// Assert
Truth.assertThat(res).isEqualTo(1000L)
staticMock.close()
}
But when I run the test, I got this error:
org.mockito.exceptions.base.MockitoException: It is not possible to
mock static methods of java.lang.System to avoid interfering with
class loading what leads to infinite loops
Why does this happen? How can I mock methods of java.lang.System class?
While Mockito since 3.4.0 version allows mocking static methods it is not allowed to mock the Thread and System static methods, see this comment on github
Finally note that Mockito forbids mocking the static methods of System (and Thread). Those methods are to much cemented into class loading which happens in the same thread. At some point, we might add instrumentation to class loading to temporarily disable the static mocks within it to make mocking these classes, too, where we also would need to disable their intensification properties. You can however easily mock Instant.now().
If you like ugly solutions you can still mock System with PowerMockito
#PrepareForTest(System.class)
public class TestCase {
#BeforeClass
public void setup() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.currentTimeMillis()).thenReturn(1000L);
}
...
But I would avoid mocking System classes if possible. You can still wrap it in method and mock this method.
To mock the static methods of java.lang.System class with the help of Mockito.
Create an interface i.e ISystem.java
public interface ISystem {
String getProperty(String name);
Long getCurrentTimeInMillis();
}
2- Create the implementation class of ISystem interface i.e ISystemImpl.java
public class ISystemImpl implements ISystem {
#Override
public String getProperty(final String name) {
return System.getProperty(name);
}
#Override
public Long getCurrentTimeInMillis() {
return System.currentTimeMillis();
}
}
3- Use Isystem.java inside your DeviceTimeProvider.java class.
public class DeviceTimeProvider {
#NonNull private final ISystem mISystem;
public DeviceTimeProvider(ISystem iSystem){
mIsystem = iSystem;
}
public Long getLocalTime(){
return mIsystem.getCurrentTimeInMillis()
}
}
4- Now finally mock the ISystem interface inside your test class.
public class DeviceTimeProviderTest {
private ISystem mISystem;
private DeviceTimeProvider sut;
#Before
public setup(){
mIsystem = mockito.mock(ISystem.class)
sut = new DeviceTimeProvider(mISystem);
}
#Test
public void getDeviceLocalTime(){
Long expectedTime = 1000L;
mockit.when(mISystem.getCurrentTimeInMillis()).thenReturn(expectedTime);
Long actualTime = sut.getLocalTime();
Assert.assertEquals(actualTime, expectedTime);
}
}
OUTPUT

Powermock verifyPrivate does not work with any()

I have a private method whose invocation I want to test without caring about the arguments. I want to test if it was called at all or not.
MyClass.java
public void doStuff(){
unload(args);
}
private void unload(List<String> args) {
//
}
So I used following:
MyClasstest.java
MyClass myClass = PowerMockito.spy(new MyClass());
myClass.doStuff();
verifyPrivate(myClass, times(1)).invoke("unload",any(List.class));
// verifyPrivate(myClass, times(1)).invoke("unload",any()); //same result with this
This test fails with following exception:
Wanted but not invoked com.MyClass.unload(
null );
However, there were other interactions with this mock .......
(actual values with which it was called)
Can verifyPrivate be called with only actual arguments & not with any()?
Here is a working example of what you are trying to do:
You might just missing the #PrepareForTest annotation, which has to point to the correct class. If your class is an external one use #PrepareForTest(MyClass.class), the example below shows it with an internal class.
#RunWith(PowerMockRunner.class)
#PrepareForTest(MyClassTest.class)
public class MyClassTest {
static class MyClass {
public void doStuff(){
unload(null);
}
private void unload(List<String> args) {
}
}
#Test
public void test() throws Exception {
MyClass myClass = PowerMockito.spy(new MyClass());
myClass.doStuff();
PowerMockito.verifyPrivate(myClass, Mockito.times(1)).invoke("unload", Mockito.any());
}
}
Note that you should consider whether you really want to do this in a UnitTest. Normally your UnitTest should not be concerned about whether a private method is used or not, it should be focused on verifying that the correct result is returned or the correct object state is reached.
By adding knowledge about the internal behaviour of the class into it, you test is tightly coupled to the implementation which might not be a good thing.

How can I mock private static method with PowerMockito?

I'm trying to mock private static method anotherMethod(). See code below
public class Util {
public static String method(){
return anotherMethod();
}
private static String anotherMethod() {
throw new RuntimeException(); // logic was replaced with exception.
}
}
Here is me test code
#PrepareForTest(Util.class)
public class UtilTest extends PowerMockTestCase {
#Test
public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc");
String retrieved = Util.method();
assertNotNull(retrieved);
assertEquals(retrieved, "abc");
}
}
But every tile I run it I get this exception
java.lang.AssertionError: expected object to not be null
I suppose that I'm doing something wrong with mocking stuff. Any ideas how can I fix it?
To to this, you can use PowerMockito.spy(...) and PowerMockito.doReturn(...).
Moreover, you have to specify the PowerMock runner at your test class, and prepare the class for testing, as follows:
#PrepareForTest(Util.class)
#RunWith(PowerMockRunner.class)
public class UtilTest {
#Test
public void testMethod() throws Exception {
PowerMockito.spy(Util.class);
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod");
String retrieved = Util.method();
Assert.assertNotNull(retrieved);
Assert.assertEquals(retrieved, "abc");
}
}
Hope it helps you.
If anotherMethod() takes any argument as anotherMethod(parameter), the correct invocation of the method will be:
PowerMockito.doReturn("abc").when(Util.class, "anotherMethod", parameter);
I'm not sure what version of PowerMock you are using, but with the later version, you should be using #RunWith(PowerMockRunner.class)
#PrepareForTest(Util.class)
Saying this, I find using PowerMock to be really problematic and a sure sign of a poor design. If you have the time/opportunity to change the design, I would try and do that first.

Powermockito: intercept all static methods

This code mocks a static void method in a class and overrides its behavior. (Taken from this question here)
#RunWith(PowerMockRunner.class)
#PrepareForTest({Resource.class})
public class MockingTest{
#Test
public void shouldMockVoidStaticMethod() throws Exception {
PowerMockito.spy(Resource.class);
PowerMockito.doNothing().when(Resource.class, "readResources", Mockito.any(String.class));
//no exception heeeeere!
Resource.readResources("whatever");
PowerMockito.verifyStatic();
Resource.readResources("whatever");
}
}
class Resource {
public static void readResources(String someArgument) {
throw new UnsupportedOperationException("meh!");
}
public static void read(String someArgument) {
throw new UnsupportedOperationException("meh!");
}
}
How can I intercept all method calls instead of individually specifying the methods?
It tried PowerMockito.doNothing().when(Resource.class) and PowerMockito.doNothing().when(Resource.class, Matchers.anything()) but these do not work.
This:
PowerMockito.doNothing().when(Resource.class, Matchers.anything())
Doesn't work because Matchers.anything() creates a matcher for Object and the above when() is trying to find methods based on the type. Try passing instead Matchers.any(String.class). This will only work for static methods with the same parameter lists. Not sure if there's a way to make a more generic override.
If you want to mock ALL static methods of a class, I think you can use PowerMockito.mockStatic(..) instead of PowerMockito.spy(..):
#Test
public void shouldMockVoidStaticMethod() throws Exception {
PowerMockito.mockStatic(Resource.class);
//no exception heeeeere!
Resource.readResources("whatever");
PowerMockito.verifyStatic();
Resource.readResources("whatever");
}
Hope it helps you.

Testing for void methods dependency using EasyMock

I have a Mainclass that I need to test which is dependent on other class.
Now I am creating a mock for that class
How to test void methods using easymock
MainClass{
mainClassMethod(){
dependencyClass.returnVoidMethod();
//other code
}
}
TestClass{
#Before
setUpMethod(){
DependencyClass dependencyClassMock = EasyMock.createMock(DependencyClass.class);
}
#Test
testMainClassMethod(){
EasyMock.expect(dependencyClassMock.returnVoidMethod()).andRetur //this is not working
dependencyClassMock.returnVoidMethod();
EasyMock.expectLastCall().anyTimes(); //If I use this, it is invoking the method.
}
}
//My dependency class code
DependencyClass implements ApplicationContextAware{
private static ApplicationContext applicationContext;
private static final String AUTHENTICATION_MANAGER = "authenticationManagers";
returnVoidMethod(){
ProviderManager pm = (ProviderManager) getApplicationContext().getBean(AUTHENTICATION_MANAGER); //this is returning null
}
//othercode
//getters and setters of application context
}
As described in the Easymock Documentation you don't put the method inside an expect() (since there is no return). You can just call the mocked method by itself and if it is in "record" mode then it is implied an expect.
dependencyClassMock.returnVoidMethod();
If you need to throw an Exception or say the method can be called anyTimes() you can use expectLastCall()
#Test
public void testMainClassMethod(){
dependencyClassMock.returnVoidMethod();
EasyMock.expectLastCall().anyTimes();
...
//later to replay the mock
EasyMock.replay(dependencyClassMock);
//now this method is actually called
dependencyClassMock.returnVoidMethod();
}
EDIT : Just noticed that you don't have the dependencyClassMock as field:
public class TestClass{
DependencyClass dependencyClassMock
#Before
setUpMethod(){
dependencyClassMock = EasyMock.createMock(DependencyClass.class);
}
...//rest of class is as described above
#dkatzel
the test is completely wrong..... you are calling manually a method and the you verify if it was called...of course it was! ...that's not the right way (my opinion)
A better way (my opinion) would be to extend the mehod class you would like to test, override that method and in the body just put a boolean variable as a flag to k now if the method was called or not....you don't even need to use EasyMock
Example
Class DependencyClass {
public void returnVoidMethod() {
[.... content ...]
}
}
Class A_test {
#Test
public void checkVoidMethodCalled() {
A_mod obj = new A_mod();
mainClassMethod();
assertTrue(obj.called);
}
Class A_mod extends DependencyClass {
boolean called = false;
#Override
public void returnVoidMethod() {
called = true;
}
}
}
You are welcome.

Categories