【问题标题】:Write junit test cases with use of log messages without using mockito使用日志消息编写 junit 测试用例而不使用 mockito
【发布时间】:2018-10-06 16:48:19
【问题描述】:

我有一个spring boot应用程序,我想为void方法编写一个junit测试用例,所以我只想测试日志是否包含特定消息。 以下是我的业务逻辑类:

public void processAdjustmentFeed(){

        ............

        if(!CollectionUtils.isEmpty(adjustmentList)){
            log.info("ADJUSTMENT FEED SIZE TO PUBLISH: {}", adjustmentList.size());
            // SOME BUSINESS LOGIC
        } else {
            log.warn("NO ADJUSTMENT FEED FOUND TO PROCESS FROM : {}", lastSuccessfulQueriedTimeStamp);
        }
    }

在我的测试课中:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AdjustmentSchedulerTest {
//
    @Autowired
    private AdjustmentScheduler adjustmentScheduler;

    @Autowired
    private AdjustmentRepository adjustmentRepository;

    @Autowired
    private AdjustmentService adjustmentService;



    @Test
    public void processAdjustmentFeed_ValidAdjustmentList() 
    {

        ....

        adjustmentScheduler.processAdjustmentFeed();

        //HERE I NEED TO CHECK FOR THE LOG MESSAGE
    }
}

不使用mockito怎么办,因为我使用的是H2数据库,我想用实际方法进行测试。谁能给我一些代码示例来做。

【问题讨论】:

  • 为什么要测试已经测试过的东西,例如日志?如果您的方法不可测试,那么听起来您的代码需要重构以使其可测试

标签: java spring-boot junit slf4j


【解决方案1】:

您应该专注于测试// SOME BUSINESS LOGIC 而不是logger。测试日志使您的测试紧密耦合,您最终会测试已经测试过的记录器代码。这不符合 unit testing principles

无论如何,如果您真的不想使用mockito,您可以随时编写自己的appender,用于记录消息。

See this for example.

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多