Java Mockito - 如何在构造函数

时间:2017-09-13 15:23:44

标签: java unit-testing mockito

我试图模拟一个具有collect函数的成员来返回一个Mock对象而不是到达函数本身。 但是,无论我如何试图模仿私人成员,它都会进入这个功能。

public class BasicReportManager implements ReportManager {
    private final ReportCollector reportCollector;

    public BasicReportManager(String id) {
        this.reportCollector = new ReportCollector(id);
    }

    private void processReport(ReportType reportTypeToProcess) {
        switch (reportTypeToProcess) {
            case REPORT1:
                Sendable collect = reportCollector.collect();
        }
    }
}

测试代码 -

ReportCollector reportData = Mockito.mock(ReportCollector.class);
Sendable sendable = Mockito.mock(Sendable.class);
Mockito.when(reportData.collect()).thenReturn(sendable);

但是,当我调用processReport()时会发生收集功能。 我该如何解决?

BasicReportManager测试版 -

basicReportManager = new BasicReportManager("1");

谢谢。

2 个答案:

答案 0 :(得分:1)

您正在嘲笑ReportCollector对象,但您从未在BasicReportManager内使用它 您应该更改BasicReportManager构造函数:

public BasicReportManager(ReportCollector reportCollector) {
    this.reportCollector = reportCollector;
}

然后你可以这样做:

ReportCollector reportData = Mockito.mock(ReportCollector.class);
Sendable sendable = Mockito.mock(Sendable.class);
Mockito.when(reportData.collect()).thenReturn(sendable);

basicReportManager = new BasicReportManager(reportData);

答案 1 :(得分:1)

如果要模拟ReportCollector使用的BasicReportManager实例,则必须在测试用例创建BasicReportManager时注入该实例。例如:

ReportCollector reportData = Mockito.mock(ReportCollector.class);
Sendable sendable = Mockito.mock(Sendable.class);
Mockito.when(reportData.collect()).thenReturn(sendable);

BasicReportManager basicReportManager = new BasicReportManager("1", reportData);

// now your test invocation on BasicReportManager will use the mocked instance of ReportCollector

您可以考虑为ReportCollector提供工厂,但这个简单的事实仍然是:为了让BasicReportManager在您的测试用例中使用ReportCollector的模拟实例,您必须能够(以某种方式!)为BasicReportManager提供该模拟实例。

相关问题