如何测试我的异步流程是否已正确提交?

时间:2019-07-11 22:01:22

标签: java asynchronous integration-testing spring-aop junit5

我有一个端点,并创建了一个AOP,它可以测量端点的执行时间,并调用一个异步服务,该时间将在数据库中记录该时间。 该服务已经在接受独立测试。 我已经对端点进行了集成测试,在此末尾,我想仅检查是否真正调用了AOP中的服务。我该怎么办?

我的端点:

@PostMapping("/doSomething")
@ResponseStatus(HttpStatus.CREATED)
@AuthorizationTime()                                            <--My AOP
public returnVO createSomething(
    @RequestBody @ApiParam(value = "requestVO") final RequestVO requestVO)
    throws Throwable {

    ResponseVO response = doing1();

    doing2();

    return response;
}

我的AOP:

@Aspect
@Component
@RequiredArgsConstructor
public class TimeAspect {

    @Autowired
    @Qualifier(SleuthThreadConfig.SLEUTH_TASK_EXECUTOR_BEAN_NAME)
    private AsyncTaskExecutor executor;

    private final TransactionAuthorizationTimeService transactionAuthorizationTimeService;

    @Around("@annotation(AuthorizationTime) && args(requestVO)")
    public Object authorizationTime(ProceedingJoinPoint joinPoint, final RequestVO requestVO) throws Throwable {
        final Instant start = Instant.now();

        final Object proceed = joinPoint.proceed();

        final Instant end = Instant.now();

        final int duration = Duration.between(start, end).getNano();

        CompletableFuture
                .runAsync(() -> transactionAuthorizationTimeService.createAuthorizationTimeEntity(
                        requestVO.getKey(),
                        durationTime)
                    , executor);

        return proceed;
    }
}

我的整合测试:

@Test
public void when_create_success() throws JSONException {


    final var vo = prepareVO; 

    RestAssured.given()
        .body(vo)
        //Act
        .contentType(ContentType.JSON)
        .post("/doSomething")
        .then()
        //Assert
        .statusCode(HttpStatus.SC_CREATED)
        .body(not(isEmptyOrNullString()))
        .body(PATH_RESULT, is(SUCESSO.code))
        .body(PATH_DATE_HOUR, not(isEmptyOrNullString()));

//TODO check if my transactionAuthorizationTimeService.createAuthorizationTimeEntity called

}

1 个答案:

答案 0 :(得分:0)

我能够使用@ Bond-JavaBond发布的示例来解决。

我的测试:

@Autowired
private TimeAspect timeAspect;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private ProceedingJoinPoint proceedingJoinPoint;

@Test
public void when_create_success() throws JSONException {


    final var vo = prepareVO; 

    RestAssured.given()
        .body(vo)
        //Act
        .contentType(ContentType.JSON)
        .post("/doSomething")
        .then()
        //Assert
        .statusCode(HttpStatus.SC_CREATED)
        .body(not(isEmptyOrNullString()))
        .body(PATH_RESULT, is(SUCESSO.code))
        .body(PATH_DATE_HOUR, not(isEmptyOrNullString()));

    timeAspect.authorizationTime(proceedingJoinPoint, vo);
    verify(proceedingJoinPoint, times(1)).proceed();
}