PowerMock does not mock correctly

不羁的心 提交于 2020-06-16 04:39:07

问题


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());
    }
}

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);
}

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?


回答1:


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

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);

Corrected working code:

Source :

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);
    }

}

Testcase :

@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);
    }
}

Attaching the pom which i have used.

<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>



回答2:


Annotate your test class with:

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

You need to add it for each case when you want to mock the object creation (for each class where you use whenNew).



来源:https://stackoverflow.com/questions/38805288/powermock-does-not-mock-correctly

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