我有一个主程序,它创建一个线程来执行某些操作。
工作线程调用长时间运行的服务并使用某种排序 回调函数来通知其响应。
public class TestingThreads {
public static void main(String[] args) {
Thread workerThread = new Thread(new WorkerThread());
workerThread.run();
}
public static class WorkerThread implements Runnable {
private ConfigService service;
@Override
public void run() {
Response response = new Response() {
@Override
public void onResponse(String result) {
//Do something on the response
}
};
Request request = new Request();
service.callSomething(request, response);
//Wait for response before exiting this run loop
}
}
public static abstract class Response {
public abstract void onResponse(String result);
}
public static class Request {
}
public static class ConfigService {
public void callSomething(Request request, Response response) {
// Call Long Running Process
}
}
}
我在为此用例创建 JUnit 测试用例时遇到问题。 您知道如何为该类(class)执行单元测试吗?
我想真正模拟我的回答,但我不知道该怎么做。 在我的单元测试中,我不想实际调用我的 ConfigService 类。
请您参考如下方法:
如果我理解正确的话,你想测试请求是否得到响应。这个回应是你喜欢看到的回应吗?
我认为您的问题是Thread
与您的代码运行同步,并且测试用例将在响应到达之前结束。
只要监听器线程处于 Activity 状态,就可以将代码保存在 JUnit Case 中。
为此,您可以使用:
Thread t = new WorkerThread();
t.join();
Thread.join();只要线程 t 处于 Activity 状态,就会阻止执行下面的代码。因此它会阻止代码并在收到响应时继续执行。