How to mock a final class with mockito

后端 未结 25 1506
日久生厌
日久生厌 2020-11-22 16:35

I have a final class, something like this:

public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}

I

25条回答
  •  梦谈多话
    2020-11-22 16:56

    This can be done if you are using Mockito2, with the new incubating feature which supports mocking of final classes & methods.

    Key points to note:
    1. Create a simple file with the name “org.mockito.plugins.MockMaker” and place it in a folder named “mockito-extensions”. This folder should be made available on the classpath.
    2. The content of the file created above should be a single line as given below:
    mock-maker-inline

    The above two steps are required in order to activate the mockito extension mechanism and use this opt-in feature.

    Sample classes are as follows:-

    FinalClass.java

    public final class FinalClass {
    
    public final String hello(){
        System.out.println("Final class says Hello!!!");
        return "0";
    }
    

    }

    Foo.java

    public class Foo {
    
    public String executeFinal(FinalClass finalClass){
        return finalClass.hello();
    }
    

    }

    FooTest.java

    public class FooTest {
    
    @Test
    public void testFinalClass(){
        // Instantiate the class under test.
        Foo foo = new Foo();
    
        // Instantiate the external dependency
        FinalClass realFinalClass = new FinalClass();
    
        // Create mock object for the final class. 
        FinalClass mockedFinalClass = mock(FinalClass.class);
    
        // Provide stub for mocked object.
        when(mockedFinalClass.hello()).thenReturn("1");
    
        // assert
        assertEquals("0", foo.executeFinal(realFinalClass));
        assertEquals("1", foo.executeFinal(mockedFinalClass));
    
    }
    

    }

    Hope it helps.

    Complete article present here mocking-the-unmockable.

提交回复
热议问题