Mockito when().thenReturn calls the method unnecessarily

后端 未结 5 2356
挽巷
挽巷 2021-02-19 02:23

I\'m working a bit on an inherited code. I\'ve written a test that is supposed to catch NullPointerException (for it is trying to call a method from null object)



        
5条回答
  •  故里飘歌
    2021-02-19 03:04

    Although it is not good coding practice to mock static method, private method or constructor. But if have some legacy code and you need to mock it. then in that case one can use Powermock with mockito.

    Steps to follow when mocking static method using powermock.
    1) use specific Runner i.e. PowerMockRunner.class.
    2) use annotation @PrepareForTest(UtilityClass.class).
    3) initialise utility class containing static method.
    4) mock static method you want.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Utility.class)
    public class mockingStaticMethod(){
    
    @Mock
    Dependency dependency;
    
    @InjectMocks
    SystemUnderTest systemUnderTest;
    
    @Test
    public void testStaticMethod(){
    
        PowerMockito.mockStatic(Utility.class);
        When(Utility.staticMethod(arguments)).thenReturn(expectedValue);
        //systemUnderTest class uses the static method present in Utility class 
        //within the methodCallingStaticMethod()
        result = systemUnderTest.methodCallingStaticMethod();
        assertEquals(expectedValue, actualValue);
    
    
       }
    }
    

提交回复
热议问题