繁体   English   中英

如何在单元测试中验证某个方法将异步执行(即在单独的线程中执行)?

[英]How can I verify in a unit test that a method will be executed asynchronously i.e. in a separate thread?

下面的方法调用方法serveThis()一个的service同步,并且该方法serveThat()在一个单独的线程,即异步:

public void doSomething() {
    service.serveThis();
    new Thread(() -> service.serveThat()).start();
}

我想在单元测试中验证service.serveThat()将异步执行,因为根据规范它不能同步执行。 因此,我想防止以后有人只是像这样删除启动新线程:

public void doSomething() {
    service.serveThis();
    // This synchronous execution must cause the test to fail
    service.serveThat();
}

可以在代码中的任何位置获取Thread.currentThread() ,因此您可以编写类似的代码并基于它进行断言(如果没有YourInterface,则可以使用Mockito以不同的方式YourInterface ):

public class ThreadChecker implements YourInterface {

    volatile Thread serveThisThread;
    volatile Thread serveThatThread;

    public void serveThis() {
        serveThisThread = Thread.currentThread();
    }

    public void serveThat() {
        serveThatThread = Thread.currentThread();
    }
}

单元测试可以是这样的,但是根据用例,可能需要其他断言:

ThreadChecker mockService = new ThreadChecker(); 

@Test
public void serveThatWillBeExecutedAsynchronously() throws Exception {
    doSomething();
    TestCase.assertFalse(mockService.serveThatThread == mockService.serveThisThread);
}

我想验证service.serveThat()是否将异步执行。

这将是。 语法是这样的。 不要测试平台。

为了实现这一点,我使用Mockito:

Thread threadServeThatRunsOn;

@Test
public void serveThatWillBeExecutedAsynchronously() throws Exception {
    doAnswer(invocation -> {
        threadServeThatRunsOn = Thread.currentThread();
        return null;
    }).when(mockService).serveThat();

    testObject.doSomething();

    verify(mockService, timeout(200)).serveThat();
    assertNotEquals(threadServeThatRunsOn, Thread.currentThread());
}

现在,如果有人修改doSomething()以使service.serveThat()能够同步运行,则此测试将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM