PowerMock调用真实方法

时间:2019-10-22 16:06:01

标签: unit-testing mockito powermockito

我正在尝试使用PowerMock监视私有方法,但是当我定义调用私有方法时应返回的内容时,它会调用该方法,并且我得到了Null Pointer Exception。什么PowerMock在这行上调用了真正的方法?

 myService= PowerMockito.spy(new MyService(myParam));

  .....
 PowerMockito.when(myService, "getCLientBy", anyString(), anyString(), anyString()).thenRetur`n(Client.of(setName, new HashSet<>())); // here it calls real method

2 个答案:

答案 0 :(得分:0)

通过添加@PrepareForTest(MyService.class)

来确保您准备将类用于间谍活动
@RunWith(PowerMockRunner.class)
// We prepare MyService for test because it's final 
// or we need to mock private or static methods
@PrepareForTest(MyService.class)
public class YourTestCase {

    //...

    @Test
    public void spyingWithPowerMock() {  

        MyService classUnderTest = PowerMockito.spy(new MyService(myParam));

        //.....

        // use PowerMockito to set up your expectation
        PowerMockito.doReturn(Client.of(setName, new HashSet<>()))
            .when(classUnderTest, "getClientBy", anyString(), anyString(), anyString());



        //...

还要确保提供正确的要调用的方法名称。

答案 1 :(得分:0)

@ user1474111和@Nkosi

我为您的示例构建了一个小型模拟。 也许您还需要在PrepareForTest批注中添加Client类。

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ MyService.class, Client.class })
    public class Example1Test {

        @Test
        public void testPowerMockito() throws Exception {

            MyService myService = PowerMockito.spy(new MyService("myParam"));

            PowerMockito.when(myService, "getClientBy", ArgumentMatchers.anyString(), ArgumentMatchers.anyString(),
                    ArgumentMatchers.anyString()).thenReturn(Client.of("setName", new HashSet<String>()));

            myService.run();

            Assert.assertEquals("setName", myService.getClient().getName());
        }
    }

    public class MyService {

        private Client client;

        public MyService(String param) { }

        private Client getClientBy(String a, String b, String c) {
            return new Client(a + b + c);
        }

        public Client getClient() {
            return this.client;
        }

        public void setClient(Client client) {
            this.client = client;
        }

        public void run() {
            setClient(getClientBy("A", "B", "C"));
        }

    }

   public class Client {

        private final String name;

        public Client(String name) {
            this.name = name;
        }

        public static Client of(String name, HashSet<String> hashSet) {
            return new Client(name);
        }

        public String getName() {
            return name;
        }

    }
相关问题