0

I am working on an API for work, we use a shared library for multiple projects for the purposing of our logging framework. The class used uses all static methods for its calls.

I am trying to Unit test an API call, I can not have it call anything on the Logging class, else it will fail.

I have tried using Powermock, but it fails on

PowerMockito.mockStatic(LoggingFramework.class); 
Mockito.when(LoggingFramework.startACall(anyString())).thenReturn("someTimestamp");

returning a

ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext

the line in LoggingFramework that throws it, is inside a static initializer block outside of any methods in the class.

needoriginalname
  • 703
  • 3
  • 9
  • 27

1 Answers1

0

In order to suppress static initialization you should use @SuppressStaticInitializationFor. So your code will look like this:

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("so.LoggingFramework") //here goes fully-qualified name of a class
public class LoggingFrameworkTest {
    @Test
    public void test() {
        //given:
        PowerMockito.mockStatic(LoggingFramework.class);
        Mockito.when(LoggingFramework.foo(anyString())).thenReturn("stub");

        //when:
        String foo = LoggingFramework.foo("ignored");

        //then:
        PowerMockito.verifyStatic(LoggingFramework.class, Mockito.times(1));
        LoggingFramework.foo(anyString()); //two-step verification of a static method

        assertThat(foo, equalTo("stub"));
    }
}

Verification of a static method is performed in two steps. It is explained here

Dmitry Khamitov
  • 3,061
  • 13
  • 21