我在 Spring 中有以下类结构。
基类,
public abstract class BaseClass {
@Autowired
protected ServiceA serviceA;
public final void handleMessage() {
String str = serviceA.getCurrentUser();
}
}
我的控制器,
@Component
public class MyController extends BaseClass {
// Some implementation
// Main thing is ServiceA is injected here
}
到目前为止,这工作正常,我可以看到ServiceA
也被正确注射。
问题出在下面的测试中嘲笑ServiceA
时。
我的控制器测试,
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class MyControllerTest {
@MockBean
private ServiceA serviceA;
@MockBean
private MyController myController;
@Before
public void init() {
when(serviceA.getCurrentUser()).thenReturn(some object);
}
@Test
public void firstTest() {
myController.handleMessage(); // ---> Throws NPE stating that serviceA is null
}
}
如前所述,它会抛出一个NullPointerException
。 我不太明白为什么尽管有when.thenReturn
嘲笑豆子时没有影响。
因为您使用的是 Spring 控制器,所以您需要通过@Autowired注释从 SpringContext 导入控制器:
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class MyControllerTest {
@MockBean
private ServiceA serviceA;
@Autowired // import through Spring
private MyController myController;
@Before
public void init() {
when(serviceA.getCurrentUser()).thenReturn(some object);
}
@Test
public void firstTest() {
myController.handleMessage(); // ---> Throws NPE stating that serviceA is null
}
}
@MockBean被添加到 SpringContext 中,因此它们将作为依赖项注入到控制器中。