Mocking final class with parameterized constructor

自古美人都是妖i 提交于 2019-12-12 03:06:49

问题


I have a final class as below

public  class firstclass{

   private String firstmethod(){

       return new secondclass("params").somemethod();

}

}


public final class secondclass{

   secondclass(String params){

        //some code

}

public String somemethod(){

         // some code 
        return somevariable";
}
}

I have to here test first class so I have mocked this as below

secondclass classMock = PowerMockito.mock(secondclass .class);
        PowerMockito.whenNew(secondclass .class).withAnyArguments().thenReturn(classMock);
Mockito.doReturn("test").when(classMock).somemethod();

But it is not mocking as I expected can anyone help me?


回答1:


  1. The method firstclass.firstmethod() is private method. So try to test this method through public method in which it is getting called.

  2. You can mock SecondClass and its final method using @RunWith(PowerMockRunner.class) and @PrepareForTest(SecondClass.class) annotations.

Please see below the working code:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(SecondClass.class)
public class FirstClassTest{


    @Before
    public void init() {

    }

    @After
    public void clear() {

    }

    @Test
    public void testfirstmethod() throws Exception{

        SecondClass classMock = PowerMockito.mock(SecondClass.class);
        PowerMockito.whenNew(SecondClass.class).withAnyArguments().thenReturn(classMock);
        Mockito.doReturn("test").when(classMock).somemethod();

        new FirstClass().firstmethod();
    }
}

Libraries used:



来源:https://stackoverflow.com/questions/40372813/mocking-final-class-with-parameterized-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!