我有一个服务类,我想为其编写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对象上的Spying有关。
我如何为这个FooService编写一个junit测试,我真正调用了methodOne
,但我嘲笑methodTwo
的返回?
答案 0 :(得分:0)
我想你把它弄复杂了。您对spy
的看法是正确的:
public class FooService {
BarService barService;
public FooService(BarService barService) {
this.barService = barService;
}
public String methodOne(int a) {
double value = methodTwo();
return "Hello from method 1 - " + value;
}
public double methodTwo() {
return 1;
}
}
public class MyTest {
private BarService barService = Mockito.mock(BarService.class);
private FooService fooService = Mockito.spy(new FooService(barService));
@Test
void test() {
doReturn(7.0).when(fooService).methodTwo();
String result = fooService.methodOne(1);
assertThat(result).isEqualTo("Hello from method 1 - 7.0");
}
}
如果您正在使用间谍,则所有未模拟的方法都将是“真实的”方法。因此,无需说doCallRealMethod()
。