[英]Mocking a autowired bean throws a NullPointerException
I have the following class structure in Spring. 我在Spring中具有以下类结构。
BaseClass , 基本类
public abstract class BaseClass {
@Autowired
protected ServiceA serviceA;
public final void handleMessage() {
String str = serviceA.getCurrentUser();
}
}
MyController , 我的控制器
@Component
public class MyController extends BaseClass {
// Some implementation
// Main thing is ServiceA is injected here
}
So far this works fine and I can see that the ServiceA
being injected properly as well. 到目前为止,这一切正常,我可以看到
ServiceA
已正确注入。
The problem is when mocking ServiceA
in the test below. 问题是在下面的测试中模拟
ServiceA
时。
MyControllerTest , MyControllerTest ,
@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
}
}
As indicated it throws a NullPointerException
. 如所示,它抛出
NullPointerException
。 I don't quite get why despite having when.thenReturn
has no affect when mocking the bean. 尽管有
when.thenReturn
在when.thenReturn
bean时没有任何影响,但我不太明白为什么。
Because you are using Spring controller, you need to import your controller from SpringContext, by @Autowired annotation: 因为您使用的是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 are added to SpringContext, so they will be injecte as a dependency to your controller. @MockBean被添加到SpringContext,因此它们将作为对控制器的依赖项注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.