1
我有这个类,在这里我想嘲笑对象创建的UrlWrapper.class惩戒新的()在Runnable的使用powerMockito
public class WorkerClass {
private final String url;
public WorkerClass(String url) {
this.url = url;
}
void performOperation(Executor executor) throws IOException {
Runnable runnable = new Runnable() {
@Override
public void run() {
UrlWrapper urlWrapper = null;
try {
urlWrapper = new UrlWrapper(url);
HttpURLConnection connection = (HttpURLConnection) urlWrapper.openConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
};
executor.execute(runnable);
}
}
这是测试代码,我试过
@RunWith(PowerMockRunner.class)
@PrepareForTest({UrlWrapper.class, WorkerClass.class})
public class TestClass {
@Before
public void init() throws Exception {
UrlWrapper urlWrapper = Mockito.mock(UrlWrapper.class);
PowerMockito.whenNew(UrlWrapper.class)
.withArguments(Mockito.anyString())
.thenReturn(urlWrapper);
}
@Test
public void test() throws IOException {
Executor executor = new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
};
WorkerClass workerClass = new WorkerClass("");
workerClass.performOperation(executor);
}
}
但它没有被嘲笑。模拟工作正常,没有Runnable。
我在这里错过了什么?
有趣的问题;我为此投了票。虽然我的回答告诉你做一些完全不同的事情。我希望,你会发现答案至少upvote值得,现在你达到了这个水平;-) – GhostCat