我想测试以下示例代码:
public class Example {
...
public void doStuff() {
...
Lift lift = new Lift();
lift.call(5);
...
}
...
}
如何“拦截” lift.call(5)?
通常,我会使用when(lift.call(anyInt()).thenReturn(...)
,但没有引用Lift对象。
答案 0 :(得分:1)
您不能仅凭嘲弄做到这一点。最干净的解决方案是重构代码,以便您可以访问它。但是,如果这不是一个选择,那么您想要的就是“ power嘲笑”。抓取“ powermock-api-mockito” +“ powermock-module-junit4”,然后执行以下操作:
import static org.mockito.Mockito.verify;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Example.class)
public class ExampleTest {
private Example testSubject;
@Mock
private Lift lift;
@Test
public void testDoStuff() throws Exception {
testSubject.doStuff();
verify(lift).call(5);
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.whenNew(Lift.class).withNoArguments().thenReturn(lift);
testSubject = new Example();
}
}
答案 1 :(得分:0)
您可以修改Example类吗?如果是,最简单的方法是提取Lift依赖项并通过构造函数提供它。像这样:
public class Example {
private final Lift lift;
public Example(Lift lift) {
this.lift = lift;
}
public void doStuff() {
this.lift.call(5);
}
}
然后,您便可以根据需要进行存根提升,因为现在您可以访问该实例。