如何在单元测试中测试异步操作中的方法调用
How can I test a method call inside an asynchronous operation in unit testing
我有一个方法,它首先执行一系列操作,然后启动一个异步任务。我想测试这个方法,但我不明白如何验证异步操作已经完成。
使用 Moсkito,我想验证 foo 方法执行了 2 次,一次在异步任务开始之前,一次在其中。问题是在 Mockito 检查异步任务时可能还没有调用异步操作中的方法。所以测试有时做,有时不做。
这是我的方法的例子:
void testingMethod() {
// some operations
someObject.foo();
CompletableFuture.runAsync(() -> {
// some other operations
someObject.foo();
});
}
以及模拟 someObject 的测试示例:
@Test
public void testingMethodTest() {
testObject.testingMethod();
Mockito.verify(someObject, Mockito.times(2)).foo();
}
有没有办法在验证方法之前等待异步操作完成。或者这是一种糟糕的测试方法,在这种情况下您有什么建议?
你可以在你的测试中 testObject.testingMethod();
之后有一个 TimeUnit.SECONDS.sleep(1);
。
附带说明一下,我什至认为您不应该测试异步发生的事情是否已完成或被调用或其他什么,这不是此功能的责任。
问题归结为被测方法调用静态方法:CompletableFuture.runAsync()
。静态方法通常对模拟和断言几乎没有控制。
即使您在测试中使用 sleep()
,您也无法断言 someObject.foo()
是否被异步调用。如果调用是在调用线程上进行的,测试仍然会通过。此外,使用 sleep()
会减慢测试速度,而 sleep()
太短会导致测试随机失败。
如果这真的是唯一的解决方案,您应该使用像 Awaitability 这样的库,它会轮询直到满足断言,并设置超时。
有几种方法可以使您的代码更易于测试:
- Make
testingMethod()
return a Future
(如您在评论中所想):这不允许断言异步执行,但它避免了等待太多;
- 将
runAsync()
方法包装在您可以模拟的另一个服务 中,并捕获参数;
- 如果您正在使用 Spring,请将 lambda 表达式移动到另一个服务中,在用
@Async
注释的方法中。这允许轻松模拟和单元测试该服务,并消除直接调用 runAsync()
的负担;
- 使用自定义执行器,并将其传递给
runAsync()
;
如果您正在使用 Spring,我建议您使用第三种解决方案,因为它确实是最干净的,并且可以避免使用 runAsync()
使您的代码混乱到处打电话。
选项 2 和 4 非常相似,只是更改了您必须模拟的内容。
如果您选择第四种解决方案,请按以下步骤操作:
更改测试 class 以使用自定义 Executor
:
class TestedObject {
private SomeObject someObject;
private Executor executor;
public TestedObject(SomeObject someObject, Executor executor) {
this.someObject = someObject;
this.executor = executor;
}
void testingMethod() {
// some operations
someObject.foo();
CompletableFuture.runAsync(() -> {
// some other operations
someObject.foo();
}, executor);
}
}
实现一个自定义 Executor
来简单地捕获命令而不是 运行 它:
class CapturingExecutor implements Executor {
private Runnable command;
@Override
public void execute(Runnable command) {
this.command = command;
}
public Runnable getCommand() {
return command;
}
}
(您也可以 @Mock
Executor
并使用 ArgumentCaptor
,但我认为这种方法更简洁)
在测试中使用 CapturingExecutor
:
@RunWith(MockitoJUnitRunner.class)
public class TestedObjectTest {
@Mock
private SomeObject someObject;
private CapturingExecutor executor;
private TestedObject testObject;
@Before
public void before() {
executor = new CapturingExecutor();
testObject = new TestedObject(someObject, executor);
}
@Test
public void testingMethodTest() {
testObject.testingMethod();
verify(someObject).foo();
// make sure that we actually captured some command
assertNotNull(executor.getCommand());
// now actually run the command and check that it does what it is expected to do
executor.getCommand().run();
// Mockito still counts the previous call, hence the times(2).
// Not relevant if the lambda actually calls a different method.
verify(someObject, times(2)).foo();
}
}
如果您正在寻找有关本主题的更多建议,请试用 Mockito.timeout()
函数,因为它专门用于测试异步方法。
示例:
verify(mockedObject,timeout(100).times(1)).yourMethod();
还有一种方法叫做after()
。也很有用。
我有一个方法,它首先执行一系列操作,然后启动一个异步任务。我想测试这个方法,但我不明白如何验证异步操作已经完成。
使用 Moсkito,我想验证 foo 方法执行了 2 次,一次在异步任务开始之前,一次在其中。问题是在 Mockito 检查异步任务时可能还没有调用异步操作中的方法。所以测试有时做,有时不做。
这是我的方法的例子:
void testingMethod() {
// some operations
someObject.foo();
CompletableFuture.runAsync(() -> {
// some other operations
someObject.foo();
});
}
以及模拟 someObject 的测试示例:
@Test
public void testingMethodTest() {
testObject.testingMethod();
Mockito.verify(someObject, Mockito.times(2)).foo();
}
有没有办法在验证方法之前等待异步操作完成。或者这是一种糟糕的测试方法,在这种情况下您有什么建议?
你可以在你的测试中 testObject.testingMethod();
之后有一个 TimeUnit.SECONDS.sleep(1);
。
附带说明一下,我什至认为您不应该测试异步发生的事情是否已完成或被调用或其他什么,这不是此功能的责任。
问题归结为被测方法调用静态方法:CompletableFuture.runAsync()
。静态方法通常对模拟和断言几乎没有控制。
即使您在测试中使用 sleep()
,您也无法断言 someObject.foo()
是否被异步调用。如果调用是在调用线程上进行的,测试仍然会通过。此外,使用 sleep()
会减慢测试速度,而 sleep()
太短会导致测试随机失败。
如果这真的是唯一的解决方案,您应该使用像 Awaitability 这样的库,它会轮询直到满足断言,并设置超时。
有几种方法可以使您的代码更易于测试:
- Make
testingMethod()
return aFuture
(如您在评论中所想):这不允许断言异步执行,但它避免了等待太多; - 将
runAsync()
方法包装在您可以模拟的另一个服务 中,并捕获参数; - 如果您正在使用 Spring,请将 lambda 表达式移动到另一个服务中,在用
@Async
注释的方法中。这允许轻松模拟和单元测试该服务,并消除直接调用runAsync()
的负担; - 使用自定义执行器,并将其传递给
runAsync()
;
如果您正在使用 Spring,我建议您使用第三种解决方案,因为它确实是最干净的,并且可以避免使用 runAsync()
使您的代码混乱到处打电话。
选项 2 和 4 非常相似,只是更改了您必须模拟的内容。
如果您选择第四种解决方案,请按以下步骤操作:
更改测试 class 以使用自定义 Executor
:
class TestedObject {
private SomeObject someObject;
private Executor executor;
public TestedObject(SomeObject someObject, Executor executor) {
this.someObject = someObject;
this.executor = executor;
}
void testingMethod() {
// some operations
someObject.foo();
CompletableFuture.runAsync(() -> {
// some other operations
someObject.foo();
}, executor);
}
}
实现一个自定义 Executor
来简单地捕获命令而不是 运行 它:
class CapturingExecutor implements Executor {
private Runnable command;
@Override
public void execute(Runnable command) {
this.command = command;
}
public Runnable getCommand() {
return command;
}
}
(您也可以 @Mock
Executor
并使用 ArgumentCaptor
,但我认为这种方法更简洁)
在测试中使用 CapturingExecutor
:
@RunWith(MockitoJUnitRunner.class)
public class TestedObjectTest {
@Mock
private SomeObject someObject;
private CapturingExecutor executor;
private TestedObject testObject;
@Before
public void before() {
executor = new CapturingExecutor();
testObject = new TestedObject(someObject, executor);
}
@Test
public void testingMethodTest() {
testObject.testingMethod();
verify(someObject).foo();
// make sure that we actually captured some command
assertNotNull(executor.getCommand());
// now actually run the command and check that it does what it is expected to do
executor.getCommand().run();
// Mockito still counts the previous call, hence the times(2).
// Not relevant if the lambda actually calls a different method.
verify(someObject, times(2)).foo();
}
}
如果您正在寻找有关本主题的更多建议,请试用 Mockito.timeout()
函数,因为它专门用于测试异步方法。
示例:
verify(mockedObject,timeout(100).times(1)).yourMethod();
还有一种方法叫做after()
。也很有用。