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