如何使用EasyMock和PowerMock模拟消费者参数

时间:2019-09-23 19:37:48

标签: powermock easymock

我有一个测试场景,需要模拟Consumer参数。

在下面的代码中,startTracer是要测试的方法。

class TracerService {

    private TracerController tracerController;

    public void startTracer(String tracerName, Object param1) {
        if (attendStartConditions(tracerName, param1)) {
            executeOnTracerControllerScope(tracerController -> tracerController.startTracer(param1));
        }
    }
    ...
}

基本上,我想测试tracerController.startTracer(param1)是否接收到param1作为参数。

Capture<Object> method1Param1 = newCapture();
tracerController.startTracer(capture(method1Param1));
expectLastCall().once();
...
tracerService.startTracer("TEST", "value1");
assertThat(method1Param1.getValue()).isEqualsTo("value1");

如何在不调用其内部代码的情况下为executeOnTracerControllerScope执行tracerController.startTracer配置EasyMock / PowerMock?

1 个答案:

答案 0 :(得分:1)

tracerController是一个模拟。因此startTracer将不会被调用。按照现在的定义,它什么也不做。做您要问的代码应该是这样的:

Capture<Object> method1Param1 = newCapture();
tracerController.startTracer(capture(method1Param1)); // no need for the expect, it's the default
replay(tracerController);
// ...
tracerService.startTracer("TEST", "value1");
assertThat(method1Param1.getValue()).isEqualsTo("value1");

当然,attendStartConditionsexecuteOnTracerControllerScope将是真实的。

在评论之后,如果您想模拟executeOnTracerControllerScope,将执行以下代码。但是,您的lambda将不再被调用。因此您将无法验证参数。

public class MyTest {
    @Test
    public void test() {
        TracerController tracerController = mock(TracerController.class);
        TracerService service = partialMockBuilder(TracerService.class)
                .withConstructor(tracerController)
                .addMockedMethod("executeOnTracerControllerScope")
                .mock();
        replay(tracerController);

        service.startTracer("tracer", "param");
    }
}

class TracerService {

    private final TracerController tracerController;

    public TracerService(TracerController tracerController) {
        this.tracerController = tracerController;
    }

    public boolean attendStartConditions(String tracerName, Object param1) {
        return true;
    }

    public void executeOnTracerControllerScope(Consumer<TracerController> tracer) {
        tracer.accept(tracerController);
    }

    public void startTracer(String tracerName, Object param1) {
        if (attendStartConditions(tracerName, param1)) {
            executeOnTracerControllerScope(tracerController -> tracerController.startTracer(param1));
        }
    }

}

interface TracerController {
    void startTracer(Object param1);
}