简体   繁体   English

如何使用Powermock模拟常规方法

[英]How to mock a regular method using Powermock

In groovy I am able to set the desired return value from a method to whatever I want in the test. 在groovy中,我能够将方法的期望返回值设置为测试中想要的任何值。 Can I mock a regular method using PowerMock? 我可以使用PowerMock模拟常规方法吗?

For eg 例如

int getYear() {
    return 2013;
}

In the test can I set something like: 在测试中,我可以设置以下内容:

expect(getYear()).andReturn(2012);

//class underTest // class underTest

class ProxyB {
    public X getDimensions(){
        GetResponseX getResponseX = client.newServiceCall().call().getResponseX();
        int d = getResponseX.getDimensions();
    }
}

I want to mock the part getResponseX.getDimensions() to return 21. 我想模拟部分getResponseX.getDimensions()以返回21。

This is the basic code for mocking a simple call. 这是模拟简单调用的基本代码。 Given the following class: 给定以下类别:

class Foo{
    int F(){
        return 42;
    }
}

You mock it by: 您通过以下方式嘲笑它:

Foo fooMock = EasyMock.createMock(Foo.class);
EasyMock.expect(fooMock.F()).andReturn(41);

The problem in your case that you need to mock the entire chain of 您所遇到的问题是您需要模拟整个链

client.newServiceCall().call().getResponseX()

For this you may need to change the way your class initially obtains a reference to client . 为此,您可能需要更改类最初获取对client的引用的方式。 EG, get it in a constructor or via a setter method. EG,通过构造函数或setter方法获取。 It might roughly resemble this: 它可能大致类似于:

class ProxyB{
    YourClient client;

    ProxyB(YourClient client){
        this.client = client;
    }

    public X getDimensions(){
        GetResponseX getResponseX = client.newServiceCall().call().getResponseX();
        int d = getResponseX.getDimensions();
    }
}

Now, when writing the unit test, you create a mock for YourClient and pass it to the constructor of the class under test. 现在,在编写单元测试时,您将为YourClient创建一个模拟并将其传递给被测类的构造函数。 This way you have complete control over what it returns from within the method ProxyB.getDimensions . 这样,您可以完全控制它从ProxyB.getDimensions方法中返回的ProxyB.getDimensions From this point you mock your way down the call chain (yes, it is a lot of mocks). 从这一点开始,您可以沿调用链进行模拟(是的,这是很多模拟)。 Eventually, the getResponseX local variable should contain your mock and you can set whatever expectations on it. 最终, getResponseX局部变量应包含您的模拟,并且您可以对其设置任何期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM