PowerMockito为什么不正确地嘲笑这个类?

时间:2015-02-23 19:25:25

标签: java unit-testing mockito powermock powermockito

我正在使用PowerMockito这是我的测试:

import com.PowerMockitoProduction;
import org.apache.commons.httpclient.HttpClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;


@RunWith(PowerMockRunner.class)
@PrepareForTest(HttpClient.class)
public class PowerMockitoTest {

    @Test(expected = UnsupportedOperationException.class)
    public void test() throws Exception {

        PowerMockito.whenNew(HttpClient.class).withNoArguments().thenThrow(new UnsupportedOperationException());

        new PowerMockitoProduction().createClient();

    }
}

此测试失败。

java.lang.AssertionError: Expected exception: java.lang.UnsupportedOperationException

这是PowerMockitoProduction的作用:

package com;

import org.apache.commons.httpclient.HttpClient;

public class PowerMockitoProduction {

    public void createClient() {
        HttpClient client = new HttpClient();
        System.out.println(client);
    }

}

我希望此代码在我的测试中基于此行创建模拟HttpClient

PowerMockito.whenNew(HttpClient.class).withNoArguments().thenThrow(new UnsupportedOperationException());

但它似乎并没有影响我的生产代码。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我弄清楚我做错了什么。我需要改变:

@PrepareForTest(HttpClient.class)

@PrepareForTest(PowerMockitoProduction.class)