java 如何在Completablefuture Junit Mockito上添加Assert< boolean>

toiithl6  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(111)

我有一个名为asynEvaluaEstadoSiniestro的服务,它返回true或false,还有一些在我的测试中被模拟的存储库。

@Service
@Slf4j
public class AsynEvaluaEstadoSiniestroImpl implements AsynEvaluaEstadoSiniestro {

  @Async("myExecutor")
  public CompletableFuture<Boolean> getEvaluacionEstadoSiniestro(DocumentRequest request) throws BusinessException {
  //do some persistances operations in repositories and return fooResult as true or false;|

  return CompletableFuture.completedFuture(fooResult);
  }
}
@InjectMocks
AsynEvaluaEstadoSiniestroImpl asynEvaluaEstadoSiniestro;

@Test
@DisplayName("Async process (1)")
void insertarSolicitudTest() throws BusinessException {
   //some when repositories functions needed for testing

CompletableFuture<Boolean> cf = asynEvaluaEstadoSiniestro.getEvaluacionEstadoSiniestro(documentRequest());
        cf.isDone();
}

当我执行sonaqube coverity时,它说:

在此测试用例中至少添加一个Assert。

我如何在这个测试中添加Assert???
我希望在这个测试中增加一个Assert。

ogq8wdun

ogq8wdun1#

每一个像样的测试用例都有这些步骤:
1.[Given] -创建输入(例如DocumentRequest示例)
1.[何时] -进行一些修改(例如,服务呼叫)
1.[Then] -检查所获得结果的正确性(Assert)
异步方法的单元测试并不像看起来那么难。幸运的是,有很多好的库可以帮助。其中一个流行的库是Awaitility
如果使用Maven作为构建工具,只需将此依赖项添加到pom.xml

<dependency>
    <groupId>org.awaitility</groupId>
    <artifactId>awaitility</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
</dependency>

为了演示,我做了一个示例服务:

public class FutureService {
    private final Executor executor = CompletableFuture.delayedExecutor(5L, TimeUnit.SECONDS);

    public CompletableFuture<Boolean> negate(boolean input) {
        return CompletableFuture.supplyAsync(() -> !input, executor);
    }
}

negate方法返回CompletableFuture<Boolean>,等待5秒后完成。这只是为了演示。
这个服务的测试是这样的。

class FutureTest {

    private final FutureService futureService = new FutureService();

    @Test
    void futureTest() throws ExecutionException, InterruptedException {
        // given (call service)
        CompletableFuture<Boolean> future = futureService.negate(true);
        // when (wait until the CompletableFuture will be done but at most 10 seconds
        Awaitility.await().atMost(Duration.ofSeconds(10L)).until(future::isDone);
        // then (in this case the returned boolean value should be false)
        Assertions.assertFalse(future.get());
    }
}

相关问题