【发布时间】:2018-05-31 17:55:47
【问题描述】:
我有一个服务类,我想为其编写 junit 测试。这是该服务类:
public class FooService {
private BarService barService;
public FooService(BarService barService) {
this.barService = barService;
}
public Foo methodOne(int a) {
double value = methodTwo();
//do some other stuff and return Foo
}
public double methodTwo() {
//do stuff
}
}
这是我的 junit 测试:
public class FooServiceTest {
@Mock
BarService barService;
FooService fooService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
fooService = Mockito.spy(new FooService(barService));
doReturn(1.0).when(fooService).methodTwo();
doCallRealMethod().when(fooService).methodOne(1);
}
@Test
public void test() {
fooService.methodOne(1);
assertThat(.....)
}
}
我的问题是,当我运行测试时,它实际上从未调用过methodOne。它只是跳过FooService 中的所有内容并直接转到asserThat(...) 行。我觉得这与监视 fooService 对象有关。
如何为这个 FooService 编写一个 junit 测试,在其中我真正调用 methodOne 但我模拟了 methodTwo 的返回?
【问题讨论】:
-
我试过这段代码,调用了真正的
methodOne。你能在methodOne(int a)中添加System.out.println("methodOne called");并检查它是否打印出来吗? -
是否有必要只模拟methodTwo?必须公开 methodTwo() 还是仅出于测试目的更改它?
标签: java junit mocking mockito stub