Unit Testing verifying a companion object method is called (mocking a companion object)

Solution 1 : add a caller function in the calling class

public class DummyWrapper {
val foo get() = DummyCompanion.Companion

public void callAStaticMethod(){
    foo.staticMechod();
}

public void callCompanionMethod(){
    foo.someCompanionMethod();
}
}

In the test class, we can use Mockito to provide a stub for the get() function and verified it is called.

@Test
fun testCase{
....
val mockCompanionObj: DummyCompanion.Companion = mock()
val wrapper = DummyWrapper()

whenever(wrapper.foo).thenReturn(mockCompanionObj)
wrapper.callCompanionMethod()
verify(mockCompanionObj).someCompanionMethod()
....
}

Solution 2: using Mockk Mocking companion object in Mockk is easy. There is no need to insert a test interfacing object in the source code.

 @Test
 fun testCompanionObject() {
    //Mock the companion object
    mockkObject(DummyCompanion.Companion)

    //define the stubbing bechavior of a companion object method
    every { DummyCompanion.Companion.companionMethod() } answers { stubMethod() }

    val testObject = DummyWrapper()

    //Call a method that calls the companion object method
    //You can verify stubMethod() is called
    testObject.callCompanionMethod()

    verify(exactly = 1) { DummyCompanion.someCompanionMethod() }
}

For details see Mockk


You can do so with PowerMock too, it'd be like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest({DummyCompanion.class})
public class staticClassTest {

    @Test
    public void testForCompanionMethod() {
       PowerMockito.mockStatic(DummyCompanion.class);
       DummyCompanion.Companion companionMock = PowerMockito.mock(DummyCompanion.Companion.class);
       Whitebox.setInternalState(
        DummyCompanion.class, "Companion",
        companionMock
       );

       DummyWrapper testObject = new DummyWrapper();
       testObject.callCompanionMethod();
       Mockito.verify(companionMock,Mockito.times(1)).someCompanionMethod();
    }
}

Kotlin creates for Java (in the Kotlin class, which is DummyCompanion in this case) a static field of its Companion subclass named Companion which can be set using PowerMock's WhiteBox.setInternalState tool to a mocked Companion instance that you can later verify method calling to.