Java 模拟自动连线bean会引发NullPointerException
我在春天有如下的班级结构 基类 我的控制者 到目前为止,这工作正常,我可以看到Java 模拟自动连线bean会引发NullPointerException,java,spring,mockito,Java,Spring,Mockito,我在春天有如下的班级结构 基类 我的控制者 到目前为止,这工作正常,我可以看到ServiceA也被正确注入 问题是在下面的测试中模拟ServiceA时 MyControllerTest 如图所示,它抛出一个NullPointerException。 我不太明白为什么尽管有when.thenReturn在模拟bean时没有影响。因为您使用的是Spring控制器,所以需要通过@Autowired注解从SpringContext导入控制器: @RunWith(SpringRunner.class) @
ServiceA
也被正确注入
问题是在下面的测试中模拟ServiceA
时
MyControllerTest
如图所示,它抛出一个NullPointerException
。
我不太明白为什么尽管有
when.thenReturn
在模拟bean时没有影响。因为您使用的是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
}
}
添加到SpringContext,因此它们将作为控制器的依赖项注入
@Component
public class MyController extends BaseClass {
// Some implementation
// Main thing is ServiceA is injected here
}
@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
}
}
@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
}
}