【问题标题】:Controller Unit test not able to autowire required beans控制器单元测试无法自动装配所需的 bean
【发布时间】:2019-01-30 12:44:43
【问题描述】:

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

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());

        }

    }

【问题讨论】:

    标签: java spring spring-mvc junit mockmvc


    【解决方案1】:

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

    创建控制器类型的变量

    @InjectMocks
    MyController myController;      
    

    在您的setUp 方法中创建mockMVC 实例时使用它,如下所示:

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

    这应该可行。

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 1970-01-01
      • 2015-04-20
      • 2014-03-11
      • 1970-01-01
      • 2016-03-29
      • 2020-10-22
      • 2016-09-27
      • 2011-09-28
      相关资源
      最近更新 更多