Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 模拟自动连线bean会引发NullPointerException_Java_Spring_Mockito - Fatal编程技术网

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
    }
}