我有这段代码-
@Component
public class ServiceA {
@Autowired
private ServiceB serviceB;
public void someMethod() {
for(Item item : items)
serviceB.foo(item);
}
}
@Component
public class ServiceB {
@Autowired
private ServiceC serviceC;
public void foo(Item item) {
if(item.boolean())
serviceC.metA();
else
serviceC.metB()
}
}
此外,我还有一个测试课程-
public serviceATest {
@Spy
@InjectMocks
private ServiceA serviceA;
@Spy
@InjectMocks
private ServiceB serviceB;
@Mock
private ServiceC serviceC;
@BeforeClass
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public generalTest() {
serviceA.someMethod();
}
}
在这种情况下-ServiceB在ServiceA中为null,而ServiceC在ServiceB中不为null。
我希望ServiceB在ServiceA中不为null,并在ServiceB中保持ServiceC不为null。
我该怎么做才能使其正常工作?
最佳答案
在这种情况下,您需要模拟在类ServiceC
中定义的ServiceB
的调用,其他情况下相同
测试代码段
@Test
public generalTest1() {
Mockito.when(serviceC.metA()).thenReturn(<Whatever is the return type of foo()>);
Mockito.when(serviceC.metB()).thenReturn(<Whatever is the return type of foo()>);
serviceB.foo();
}