控制器单元测试无法自动连线所需的bean

时间:2019-01-30 12:44:43

标签: java spring spring-mvc junit mockmvc

我正在尝试为spring控制器编写单元测试, myService 类在 myController 中自动装配,我模拟了myService类,但是在调试代码时即将

myService = null

我无法为我的控制器注入此服务。

   @RunWith(MockitoJUnitRunner.class)
    public class TestManageDevices {

        private MockMvc mockMvc;

        @Mock
        MyService myService;

        @Before
        public void setUp() {
            mockMvc = MockMvcBuilders.standaloneSetup(new MyController())
                    .build();
        }

        @Test
        public void shouldPass() throws Exception {
            Mockito.doNothing().when(myService).someMethod(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
            JobResponse jobResponse = JobResponse.builder().responseCode(0).build();
            jobResponse.requestObj = "mockedStringObject";

            RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/pathfortest")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .param("id", Mockito.anyString());

            MvcResult result = mockMvc.perform(requestBuilder).andReturn();


            System.out.println(result.getResponse().getContentAsString());

            MockHttpServletResponse response = result.getResponse();


            Assert.assertEquals(HttpStatus.CREATED.value(), response.getStatus());

        }

    }

1 个答案:

答案 0 :(得分:2)

您正在使用new MyController()方法中的setUp手动更新控制器,因此不会注入依赖项。

创建类型为controller的变量

@InjectMocks
MyController myController;      

mockMVC方法中创建setUp实例时,请使用以下方法:

mockMvc = MockMvcBuilders.standaloneSetup(myController).build();

这应该有效。