如何使用mockito模拟JobExecution.builder()并模拟DynamoDBMapper进行单元测试?

ne5o7dgx  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(167)

我想使用mockito测试下面的方法。jobExecution对象保存在DynamoDB中。请参考下面的代码。

private void saveOrUpdateToDynamoDb(final JobExecution existingJobExecution) {
final JobExecution jobExecution = JobExecution.builder().jobMasterId("12").jobType("lamda")
                    .jobAction("Entry message load into MC").status("running").startDate(startTime).referenceId("225")
                        .payload(messageBody).ttlExpiry(5259600+Instant.now().getEpochSecond()).build();
saveOrUpdateToDynamoDb(jobExecution);
}

private void saveOrUpdateToDynamoDb(final JobExecution existingJobExecution) {
    dbMapper.save(existingJobExecution,
                    new TableNameOverride(String.format(STRING_CONCAT, CAPABILITY_CODE, envName, TABLE_NAME)).config());
}
brgchamk

brgchamk1#

如果您希望模拟saveOrUpdateToDynamoDb,以便在测试期间调用该方法,而不实际尝试连接到DB,则可以执行以下操作:

public class Foo {

    // @VisibleForTesting makes it obvious why this is package-private, not private
    @VisibleForTesting
    DynamoDBMapper dbMapper = ***

    private void saveOrUpdateToDynamoDb(final JobExecution existingJobExecution) {
        final JobExecution jobExecution = JobExecution.builder().jobMasterId("12").jobType("lamda")
            .jobAction("Entry message load into MC").status("running").startDate(startTime).referenceId("225")
            .payload(messageBody).ttlExpiry(5259600+Instant.now().getEpochSecond()).build();
        saveOrUpdateToDynamoDb(jobExecution);
    }

    @VisibleForTesting
    void saveOrUpdateToDynamoDb(final JobExecution existingJobExecution) {
        dbMapper.save(existingJobExecution,
            new TableNameOverride(String.format(STRING_CONCAT, CAPABILITY_CODE, envName, TABLE_NAME)).config());
    }

}

然后在您的测试中(应该在同一个包中)

@Test
    void testXYZ() {
        Foo foo = new Foo();
        doNothing().when(foo.saveOrUpdateToDynamoDb(any(JobExecution.class), any(TableNameOverride.class)));

        // test now
    }

对于调用代码来说,这看起来像是成功的DB保存。

相关问题