JUnit在带有@Autowired注释的Spring Boot中不起作用

时间:2018-07-22 12:11:23

标签: spring-boot junit

我有一个Spring Boot应用程序,正在其中创建REST Web服务 使用MVC模式。

我有一个控制器,服务和DAO类,并且使用@Autowired批注来调用服务和DAO层的方法。

当我使用Mockito创建JUnit测试时,值将进入控制器,但不会从控制器进入服务类。

这是代码示例:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppplicationConfiguration.class})
public class ExternalControllerTest {


    private MockMvc mockMvc;


    @InjectMocks
    private MyController myController;


    @MockBean
    myService myService;


    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .standaloneSetup(myController)

                .build();
    }


    @Test
    public void testListCluster() throws Exception {


        Input emrInput = new Input();
        emrInput.setId("200004773");
        emrInput.setName("test");

        String expected = "{\"status\":\"Success\",\"message\":\"Success\",\"data\":\"somevalue\"}";

        AutomateRestResponse response = new AutomateRestResponse<JsonObject>();

        response.setMessage("Success");
        response.setStatus("Success");
        response.setData("somevalue");
        Mockito.when(
                externalService.listCluster(emrInput)
        ).thenReturn(response);

        mockMvc.perform(post("/v1/gerData"))


                .andExpect(status().isOk())

                .andExpect(jsonPath("$.status", is("Success")));


        verify(externalService, times(1)).listCluster(emrInput);


        RequestBuilder requestBuilder = MockMvcRequestBuilders

                .post("/v4/listCluster")

                .accept(MediaType.APPLICATION_JSON).content(emrInputJosn)

                .contentType(MediaType.APPLICATION_JSON);


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


        System.out.println("response body1" + result.getResponse()

                .getContentAsString());
    }`

请帮助我。

4 个答案:

答案 0 :(得分:0)

从您的问题中不清楚您要模拟什么。

无论如何,由于测试中实际执行的是被模拟的服务而不是您的模拟服务,因此您应该无法调试被模拟的服务/目标。

如果要测试控制器,则可以模拟服务或dao并定义它们将返回的响应,然后验证从控制器获得的响应是​​否符合预期。

答案 1 :(得分:0)

@EnableWebMvc @SpringBootApplication(scanBasePackages = {“ com.yourPackage.external”})

公共类YourApplication扩展了org.springframework.boot.web.support.SpringBootServletInitializer {

public static void main(String[] args) {
    SpringApplication.run(applicationClass, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(applicationClass);
}

private static Class<Application> applicationClass = Application.class;

}

答案 2 :(得分:0)

根据您粘贴的内容,您可以执行以下操作:

  1. 如果您使用的是@RunWith(SpringJUnit4ClassRunner.class) [最好更改为@RunWith(SpringRunner.class)],则使用

    @MockBean private MyService externalService;

OR

  1. 使用@RunWith(MockitoJUnitRunner.class)

    @MockBean private MyService externalService;

@InjectMocks private MyController controller = new MyController(externalService);

有关详细信息,请检出:-testing web in spring boot

答案 3 :(得分:0)

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppplicationConfiguration.class})
public class ExternalControllerTest {


    private MockMvc mockMvc;


    @InjectMocks
    private MyController myController  ;



    @MockBean
    myService myService;



    @Before
    public void setUp() throws Exception {
          MockitoAnnotations.initMocks(this);
            mockMvc = MockMvcBuilders
                    .standaloneSetup(myController)

                    .build();
    }


    @Test
    public void testListCluster() throws Exception {


Input emrInput = new Input();
emrInput.setId("200004773");
emrInput.setName("test");

String expected = "{\"status\":\"Success\",\"message\":\"Success\",\"data\":\"somevalue\"}";

AutomateRestResponse response =  new AutomateRestResponse<JsonObject>();

response.setMessage("Success");
response.setStatus("Success");
response.setData("somevalue");
Mockito.when(
        externalService.listCluster(emrInput)
                ).thenReturn(response);

mockMvc.perform(post("/v1/gerData"))


.andExpect(status().isOk())



.andExpect(jsonPath("$.status", is("Success")));



verify(externalService, times(1)).listCluster(emrInput);



RequestBuilder requestBuilder = MockMvcRequestBuilders

.post("/v4/listCluster")

.accept(MediaType.APPLICATION_JSON).content(emrInputJosn)

.contentType(MediaType.APPLICATION_JSON);



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


System.out.println("response body1"+ result.getResponse()

.getContentAsString());
}
}