I am testing some legacy code and would like to mock any calls to a static logger method: LoggerFact.getLogger(Class class, String MethodName)
, here is what I tried:
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFact.class, MyClass.class, Logger.class})
public class MyClassTest
{
@Before
public void prepare() throws Exception
{
Logger mockedLogger = Mockito.mock(Logger.class);
PowerMockito.mockStatic(LoggerFact.class);
PowerMockito.when(LoggerFact.getLogger(MyClass.class, "test"))
.thenReturn(mockedLogger);
}
//My tests
}
The class that I am testing:
public class MyClass
{
public String methodToBeTested()
{
Logger logger = LoggerFact.getLogger(this.getClass(), "test");
logger.info("This is a test");
//some logic
return "SUCCESS";
}
}
But I am recieving this error when I do this from the prepare when():
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
Did I miss something? I checked a lot of older posts about this issue, but nothing worked for me.
Working example here. Tested with JDK 8 and JDK 11.
The following works for me. (I have found that the order of initialization can be crucial):
@RunWith(PowerMockRunner.class)
@PrepareForTest(LoggerFact.class)
public class MyClassTestCase {
private MyClass myClass = null;
@Before
public void setUp() {
PowerMockito.mockStatic(LoggerFact.class);
}
@Test
public void testMethodToBeTested() {
Logger mockLogger = Mockito.mock(Logger.class);
PowerMockito.when(LoggerFact.getLogger(eq(MyClass.class),eq("test"))).thenReturn(mockLogger);
myClass = new MyClass();
// test
myClass.methodToBeTested();
verify(mockLogger, times(1)).info(eq("This is a test"));
}
}
As requested, from build.gradle
in the example link above, here are the versions of libraries:
dependencies {
testImplementation 'junit:junit:4.13.1'
testImplementation 'org.mockito:mockito-core:3.6.0'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.7'
testImplementation 'org.powermock:powermock-module-junit4:2.0.7'
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments