如何编写REST控制器端点的单元测试而不在Spring-boot

时间:2016-08-18 23:25:32

标签: rest junit spring-boot mockito mockmvc

我必须在Spring-boot中为Web Service编写单元测试,它应该从Controller执行测试并流入Service类。 我正在使用ServiceMile的@Mock注释和Controller的@InjectMock,因此应用程序流永远不会进入Service类,(它返回一个null)。

如果没有Service类的@Mock注释,我会收到一个空点异常。

我不想模拟Service类,我想用同一个测试单元测试Service类。

这是我的REST控制器。

 @RestController
 public class AddressController {
 @Autowired
 private GetAddressService getAddressService;

@RequestMapping(value=ApplicationConstant.ADDRESS_URI,method=RequestMethod.G    ET,produces = { ApplicationConstant.APP_RESP_TYPE })
public @ResponseBody SampleResponse getAddress(
        @RequestParam(value="id",required=true) String hcId,
        @RequestParam(value="mbrNbrbr",required=true) String mbrNbr,
        ){

    System.out.println("Request ID in Controller :"+Id);
    String responseid = getAddressService.getAddress(Id);

    SampleResponse smapleResp = new SampleResponse();
    System.out.println("Response ID in Controller :"+Id);
    smapleResp.setResponseid(responseid);
    return smapleResp;

这是我的服务类

 @Service
public class GetAddressServiceImpl implements GetAddressService {
@Override
public String getAddress(String id) {

    System.out.println("ID in Service : " + id);
    return id;
}
}

我有一个Abstract测试类,它扩展到Abstract Controller测试类,最后​​是我的地址控制器测试类,它有@Test方法。

Abstarct测试课程:

 @RunWith(SpringJUnit4ClassRunner.class)
 @SpringApplicationConfiguration(classes = Application.class)
 public abstract class AbstractTest {
  }

Abstarct控制器测试类:

@WebAppConfiguration 
public abstract class AbstractControllerTest extends AbstractTest {

//mockmvc stimulates Http interactions
protected MockMvc mockMvc; 

@Autowired
protected WebApplicationContext webApplicationContext;


protected void setUp(){
    mockMvc =   MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}


protected void setUp(AddressController addressController){
    mockMvc = MockMvcBuilders.standaloneSetup(addressController).build();
}
}

最后我的地址测试课程:

   @TestExecutionListeners
    public class AddressMockControllerTest extends AbstractControllerTest  {

    @Mock
    private GetAddressService getAddressService;

    @InjectMocks
    private AddressController addressController;

    private String MockURI ="/v1/legacy/member/Contact/Address? id=55555&mbrNbr=20&id=ABC&productid=1FGQ&sourceid=STAR&addressuid=adasdsa";

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
        setUp(addressController);       
        }


    @Test
    public void test(){
        System.out.println("In Unit test");

    }

    @Test
    public void testgetAddress() throws Exception {


     System.out.println("In Unit test");

     MvcResult result =  this.mockMvc.perform(
                   MockMvcRequestBuilders.get(MockURI)
                  .accept(MediaType.APPLICATION_JSON))
                  .andReturn(); 


     String content = result.getResponse().getContentAsString();

        System.out.println("In Unit test and content is " + content);   
    }

引导主类:

 public class Application extends SpringBootServletInitializer{

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

@Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
    return application.sources(ApplicationInitializer.class);
}

应用程序初始化程序:

    @Configuration

@EnableAutoConfiguration
@ComponentScan(value={"com.ABC"})
@EnableConfigurationProperties
public class ApplicationInitializer {

    @Bean
    @ConditionalOnMissingBean(RequestContextListener.class)
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }

    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        ServletRegistrationBean registration = new ServletRegistrationBean(
                dispatcherServlet);
        registration.addUrlMappings("/");
        return registration;
    }

    @Bean
    public ServletRegistrationBean dynamicLogbackLevelServletRegistration() {

        return new ServletRegistrationBean(new DynamicLogbackLevelServlet(),"/loglevel");

    }


    @Order(Ordered.HIGHEST_PRECEDENCE)
    public FilterRegistrationBean contextFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        RequestFilter contextFilter = new RequestFilter();
        registrationBean.setFilter(contextFilter);
        registrationBean.setOrder(1);
        return registrationBean;
    }


    @Bean
    public ApplicationContextProvider applicationContextProvider(){
        return new ApplicationContextProvider();
    }

}

2 个答案:

答案 0 :(得分:0)

不确定这是否有效但是基于另一个SO帖子:https://stackoverflow.com/a/32294564/1499549

如果您使用跑步者,看起来您不应该使用standaloneSetup()。

public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

然后删除@InjectMocks注释并将其替换为@Autowired

//@Mock
//private GetAddressService getAddressService;

//@InjectMocks
@Autowired
private AddressController addressController;

private String MockURI ="/v1/legacy/member/Contact/Address?id=55555&mbrNbr=20&id=ABC&productid=1FGQ&sourceid=STAR&addressuid=adasdsa";

@Before
public void setUp(){
    setUp();       
}

@Test
public void test(){
    System.out.println("In Unit test");
}

答案 1 :(得分:0)

BTW,Spring Boot现在基于@MockedBean注释built in support for mocking and spying beans。也许你想调查它。