PowerMock无法正确模拟 [英] PowerMock does not mock correctly

查看:211
本文介绍了PowerMock无法正确模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的方法,该方法应获取一个url并通过get请求从该url检索数据.该方法如下所示:

I have written a simple method which should take a url and retrieve the data from this url via a get request. The method looks like this:

public String getResponse(String connectionUrl) throws HttpException {

    HttpURLConnection connection = null;

    try {
        URL url = new URL(connectionUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            throw new HttpException("Response code was " + responseCode + " (should be 200)");
        }

        Scanner scanner = new Scanner(connection.getInputStream()).useDelimiter("\\A");
        String response = scanner.hasNext() ? scanner.next() : "";

        connection.disconnect();
        scanner.close();

        return response;

    } catch (IOException e) {

        if (connection != null) {
            connection.disconnect();
        }

        throw new HttpException(e.getMessage(), e.getCause());
    }
}

现在,我正在为此方法编写单元测试.我将PowerMock与Mockito和JUnit结合使用来编写测试.有问题的测试如下:

Now I am writing unit tests for this method. I use PowerMock with Mockito and JUnit to write my tests. The test in question looks like this:

@Test
public void getResponse_NormalResponse() throws Exception {

    String expectedResponse = "This is the expected response text!";
    URL url = PowerMockito.mock(URL.class);
    HttpURLConnection connection = PowerMockito.mock(HttpURLConnection.class);
    InputStream inputStream = PowerMockito.mock(InputStream.class);
    Scanner scanner = PowerMockito.mock(Scanner.class);

    PowerMockito.whenNew(URL.class).withArguments(REQUEST_URL).thenReturn(url);
    PowerMockito.whenNew(Scanner.class).withArguments(inputStream).thenReturn(scanner);
    PowerMockito.when(url.openConnection()).thenReturn(connection);

    // Response code mocked here
    PowerMockito.when(connection.getResponseCode()).thenReturn(200); 

    PowerMockito.when(connection.getInputStream()).thenReturn(inputStream);
    PowerMockito.when(scanner.hasNext()).thenReturn(true);
    PowerMockito.when(scanner.next()).thenReturn(expectedResponse);

    HttpClient httpClient = new HttpClient();
    String actualResponse = httpClient.getResponse(REQUEST_URL);

    Assert.assertEquals("Response is wrong!", expectedResponse, actualResponse);
}

但是,当我运行测试时,因为响应代码为404,所以抛出HttpException.测试是使用PowerMockRunner运行的.我做错了什么,为什么此测试无法正常工作?

But when I run the test, a HttpException is thrown because the response code is 404. The tests are run with the PowerMockRunner. What did I do wrong, why isn't this test working correctly?

推荐答案

由于您使用的是whenNew,因此还必须在@PrepareForTest下添加在其中创建新对象的类.

You have to also add the class where new object is created under @PrepareForTest since you are using whenNew.

您的课程似乎是HttpClient

Your class seems to be HttpClient

@PrepareForTest({ URL.class, Scanner.class ,HttpClient.class})

解决了您的测试中的另一个问题. 添加了缺少的期望.

Solved one more problem with your test . Added the missing expectation.

PowerMockito.when(scanner.useDelimiter("\\A")).thenReturn(scanner);

正确的工作代码:

来源:

public class HttpClient {

    public String getResponse(String connectionUrl) throws HttpException {

        HttpURLConnection connection = null;

        try {
            URL url = new URL(connectionUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                throw new HttpException("Response code was " + responseCode
                        + " (should be 200)");
            }

            Scanner scanner = new Scanner(connection.getInputStream())
                    .useDelimiter("\\A");
            String response = scanner.hasNext() ? scanner.next() : "";

            connection.disconnect();
            scanner.close();

            return response;

        } catch (IOException e) {

            if (connection != null) {
                connection.disconnect();
            }

            throw new HttpException(e.getMessage(), e.getCause());
        }
    }

}

class HttpException extends Exception {

    public HttpException(String string) {
        super(string);
    }

    public HttpException(String message, Throwable cause) {
        super(message, cause);
    }

}

测试用例:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ URL.class, Scanner.class, HttpClient.class })
public class HttpClientTest {

    private static final String REQUEST_URL = "http://wwww.google.com";

    @Test
    public void getResponse_NormalResponse() throws Exception {

        String expectedResponse = "This is the expected response text!";
        URL url = PowerMockito.mock(URL.class);
        HttpURLConnection connection = PowerMockito
                .mock(HttpURLConnection.class);
        InputStream inputStream = PowerMockito.mock(InputStream.class);
        Scanner scanner = PowerMockito.mock(Scanner.class);

        PowerMockito.whenNew(URL.class).withArguments(REQUEST_URL)
                .thenReturn(url);
        PowerMockito.whenNew(Scanner.class).withArguments(inputStream)
                .thenReturn(scanner);
        PowerMockito.when(scanner.useDelimiter("\\A")).thenReturn(scanner);

        PowerMockito.when(url.openConnection()).thenReturn(connection);

        // Response code mocked here
        PowerMockito.when(connection.getResponseCode()).thenReturn(200);

        PowerMockito.when(connection.getInputStream()).thenReturn(inputStream);
        PowerMockito.when(scanner.hasNext()).thenReturn(true);
        PowerMockito.when(scanner.next()).thenReturn(expectedResponse);

        HttpClient httpClient = new HttpClient();
        String actualResponse = httpClient.getResponse(REQUEST_URL);

        Assert.assertEquals("Response is wrong!", expectedResponse,
                actualResponse);
    }
}

附上我用过的pom.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>MockItToExample</groupId>
    <artifactId>MockItToExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>

        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>1.6.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.6.3</version>
        </dependency>

    </dependencies>

    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

这篇关于PowerMock无法正确模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆