nickylin / powermock

Automatically exported from code.google.com/p/powermock
Apache License 2.0
0 stars 0 forks source link

PowerMock and Easy mock doesn't work as expected when two objects of same class is under test #496

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Have a class and a method which creates two objects of final class (Example: 
java.net.URL) with different arguments.
2. Write a unit test which sends different mockURL object for each instance 
based on argument.
3.Expect for a method on mockURL object (Ex: openConnection) and return another 
mock object

Below is the sample code which repro this issue:

Class Under Test:
=================
import java.io.IOException;
import java.net.URL;

public class Test2URL {
    public void urls() throws IOException {
        URL url1 = new URL("abcd");
        URL url2 = new URL("xyz");
        System.out.println(url1.openConnection());
        System.out.println(url2.openConnection());
    }
}

JUnit test case:
================

import static org.easymock.EasyMock.expect;

import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@PrepareForTest ({URL.class, Test2URL.class, HttpsURLConnection.class})
@RunWith (PowerMockRunner.class)
public class TestTest2URL {

    @Test
    public void test() throws Exception {
        Test2URL original  = new Test2URL();
        URL abcd = PowerMock.createMockAndExpectNew(URL.class, "abcd");
        URLConnection abcdConnection = PowerMock.createMock(HttpsURLConnection.class);
        expect(abcd.openConnection()).andReturn(abcdConnection);
        URL xyz = PowerMock.createMockAndExpectNew(URL.class, "xyz"); 
        URLConnection xyzConnection = PowerMock.createMock(HttpsURLConnection.class);
        expect(xyz.openConnection()).andReturn(xyzConnection);
        PowerMock.replayAll();
        original.urls();
        PowerMock.verifyAll();
    }
}

What is the expected output? 
I am expecting below message in console:
EasyMock for class javax.net.ssl.HttpsURLConnection
EasyMock for class javax.net.ssl.HttpsURLConnection

What do you see instead?
EasyMock for class javax.net.ssl.HttpsURLConnection
null

What version of the product are you using? On what operating system?
1.5.1 (powermock-mockito-1.5.1-full.jar)

Original issue reported on code.google.com by RKmoor...@gmail.com on 29 Apr 2014 at 2:09