我有一个测试场景,需要模拟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?
答案 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");
当然,attendStartConditions
和executeOnTracerControllerScope
将是真实的。
在评论之后,如果您想模拟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);
}