使用PowerMockito

时间:2017-10-17 15:33:43

标签: unit-testing mockito junit4 powermock powermockito

我有一个名为Utility的项目,它的名称为Util,如下所示:

public class Util {
    public static String verify() {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet getRequest = new HttpGet("Endpoint");
        HttpResponse response = httpClient.execute(getRequest);
        // Parsing the response as String
        String resp = .......
        return resp;
    }
}

我有一个名为Consumer的另一个项目,它有一个名为Service的类,如下所示:

public class Service {
    public String verify() {
        String resp = Util.verify();
        return resp;
    }
}

我已将Utility添加为Consumer的依赖项:

<dependency>
    <groupId>com.my.company</groupId>
    <artifactId>utility</artifactId>
    <version>0.0.1</version>
    <scope>provided</scope>
</dependency>

我有一个Service课程的单元测试用例,我在Util类中使用PowerMockito作为:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Util.class })
public class ServiceTest {
    Service service = new Service();
    @Before
    public void setUp() throws Exception {
        PowerMockito.mockStatic(Util.class);
        PowerMockito.when(Util.verify()).thenReturn("mockedResponse");
    }

    @Test
    public void testVerify() {
        String resp = service.verify();
        assertEquals(resp, "mockedResponse");
    }
}

此测试会抛出ProtocolSocketFactory的NotFoundException。有谁知道为什么我看到这个例外?我试图模拟Util类,但PowerMockito尝试在模拟之前初始化类。如果我在项目HttpClient的{​​{1}}中添加pom.xml作为依赖项,则错误消失并且模拟成功。

我使用的Powermockito版本是1.6.2

Consumer

0 个答案:

没有答案