問題描述
在我的 Android 項目中,我有一個類擴展了 處理線程:
In my Android project, I have a class extends HandlerThread:
public class MyHandlerThread extends HandlerThreads {
private Handler mHandler;
…
public void doAsyncTask(MyAsyncTask task) {
mHandler = new Handler(this.getLooper());
mHandler.post(task);
}
}
上述函數的參數類型MyAsyncTask
是一個類擴展Runnable
:
The above function's parameter type MyAsyncTask
is a class extends Runnable
:
public abstract class MyAsyncTask implements Runnable {
@Override
public void run() {
doTask();
}
public abstract void doTask();
}
我有一個 MyWorker
類,它有一個函數使用 MyHandlerThread
類:
I have a MyWorker
class which has a function uses MyHandlerThread
class:
public class MyWorker {
public void work() {
MyHandlerThread handlerThread = new MyHandlerThread();
handlerThread.start();
handlerThread.doAsyncTask(new MyAsyncTask() {
@Override
doTask() {
int responseCode = sendDataToServer();
}
});
}
}
我想使用 Mockito 對 中的
類(例如檢查服務器 work()
函數進行單元測試MyWorkerresponseCode
).如何在 Mockito 中做到這一點?
I want to use Mockito to unit test the work()
function in MyWorker
class (e.g. check the server responseCode
). How to do it in Mockito?
推薦答案
你想測試什么?我的工人
?MyHandlerThread
?匿名 MyAsyncTask
?一起來?可能是個壞主意,特別是如果匿名 MyAsyncTask
依賴于實際的服務器響應(這會阻止這成為一個好的單元測試,因為那時您正在測試整個系統).所以,我會把整個事情分成幾個部分,分別測試所有這些部分.如果您已經這樣做了,那么您可以通過集成測試將多個部分與真實服務器一起檢查.
WHAT do you want to test? MyWorker
? MyHandlerThread
? the anonymous MyAsyncTask
? All toegether? Probably a bad idea, especially if the anonymous MyAsyncTask
relies on an actual server response (which would prevent this from being a good unit test, since you are testing a whole system then). So, I would split the whole thing into parts and test all these parts seperately. If you have done so, then you can check multiple parts toegether against a real server with an integration tests.
要測試 MyHandlerThread,你可以引入一個 HandlerFactory,模擬它,從而確保處理程序被正確調用.
To test the MyHandlerThread, you could for example introduce a HandlerFactory, mock that and thus ensure that the handler was called correctly.
public class MyHandlerThread extends HandlerThreads {
private HandlerFactory handlerFactory; // <- Add setter
…
public void doAsyncTask(MyAsyncTask task) {
Handler mHandler = handlerFactory.createHandler(this.getLooper());
mHandler.post(task);
}
}
易于測試的單元.MyAsyncTask
簡短而抽象,老實說,我不會測試它.在那里沒有太多收獲,因為它實際上并沒有多大作用.MyWorker
呢?取決于,但你可以,例如,為 MyHandlerThread
添加一個 getter/setter,允許你模擬它.將您的匿名類提取到一個真實的類中可能會讓您也可以獨立于其他類來測試該類.
Easily testable unit. MyAsyncTask
is short and abstract, honestly, I wouldn't test that. Not much to gain there, since it doesn't actually do much. And the MyWorker
? Depends, but you could, for example, add a getter/setter for the MyHandlerThread
, allowing you to mock that. Extracting your anonymous class into a real one would probably allow you to test that one, too, independent of the others.
這篇關于在我的情況下,用戶 Mockito 對執行異步任務的函數進行單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!