繁体   English   中英

调用REST API的Spring MVC控制器的错误单元测试

[英]Error Unit Testing of Spring MVC Controllers calling REST API

我在小型应用程序中对spring MVC控制器进行单元测试,但收到以下错误:

INFO: **Initializing Spring FrameworkServlet ''**
Oct 30, 2015 5:37:38 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization started
Oct 30, 2015 5:37:38 PM org.springframework.test.web.servlet.TestDispatcherServlet initServletBean
INFO: FrameworkServlet '': initialization completed in 2 ms
Running com.sky.testmvc.product.controller.ProductSelectionControllerTest
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.031 sec <<< FAILURE!
testRoot(com.sky.testmvc.product.controller.ProductSelectionControllerTest)  Time elapsed: 0.031 sec  <<< FAILURE!
*java.lang.AssertionError: **Status expected:<200> but was:<204>***
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:549)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)

其余控制器如下:

 @RestController
    public class ItemRestController {   

        @Autowired
        ItemService catalogueService;   
        @Autowired
        LocationService locationService;   

        @RequestMapping(value = "/product/{customerId}", produces = {MediaType.APPLICATION_JSON_VALUE}, method = RequestMethod.GET)
        public ResponseEntity<List<Item>> listCustomerProducts(@PathVariable("customerId") int customerId) {

            Integer customerLocation=(Integer) locationService.findLocationByCustomerId(customerId);
            List<Product> products = catalogueService.findCustomerProducts(customerLocation);

            if(products.isEmpty()){
                return new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<List<Product>>(products, HttpStatus.OK);
        }   
    }



  @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(classes = {TestContext.class, AppConfiguration.class}) //load your mvc config classes here

    public class ItemControllerTest {

        private MockMvc mockMvc;
        @Autowired
        private ItemService productServiceMock;
        @Autowired
        private WebApplicationContext webApplicationContext;

        @Before
        public void setUp() {
            Mockito.reset(productServiceMock);
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }



  @Test
public void testRoot() throws Exception 
{      

    Product prod1= new Product(1L,"Orange", new ProductCategory(1,"Sports"),new CustomerLocation(2,"London"));
    Product prod2= new Product(2L,"Banana", new ProductCategory(1,"Sports"),new CustomerLocation(2,"London"));

    when(productServiceMock.findCustomerProducts(1L)).thenReturn(Arrays.asList(prod1, prod2));

    mockMvc.perform(get("/product/{id}", 1L))
    .andExpect(status().isOk())
    .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
    .andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].productId", is(1)))
            .andExpect(jsonPath("$[0].productName", is("Orange")))
            .andExpect(jsonPath("$[1].productId", is(2)))
            .andExpect(jsonPath("$[1].productName", is("Banana")));

    verify(productServiceMock, times(1)).findCustomerProducts(1L);
    verifyNoMoreInteractions(productServiceMock);       
}

    }

请参见下面的TestContext:

 @Configuration
    public class TestContext {

        private static final String MESSAGE_SOURCE_BASE_NAME = "i18n/messages";

        @Bean
        public MessageSource messageSource() {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();

            messageSource.setBasename(MESSAGE_SOURCE_BASE_NAME);
            messageSource.setUseCodeAsDefaultMessage(true);

            return messageSource;
        }

        @Bean
        public ItemService catalogueService() {
            return Mockito.mock(ItemService .class);
        }
    }


 @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "com.uk.springmvc")
    public class AppConfiguration extends WebMvcConfigurerAdapter{

        private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/views/";
        private static final String VIEW_RESOLVER_SUFFIX = ".jsp";


        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setViewClass(JstlView.class);
            viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
            viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);
            registry.viewResolver(viewResolver);
        }

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("/static/");
        }

        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }

        @Bean
        public SimpleMappingExceptionResolver exceptionResolver() {
            SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();

            Properties exceptionMappings = new Properties();

            exceptionMappings.put("java.lang.Exception", "error/error");
            exceptionMappings.put("java.lang.RuntimeException", "error/error");

            exceptionResolver.setExceptionMappings(exceptionMappings);

            Properties statusCodes = new Properties();

            statusCodes.put("error/404", "404");
            statusCodes.put("error/error", "500");

            exceptionResolver.setStatusCodes(statusCodes);

            return exceptionResolver;
        }


    }

如前所述,该应用程序正常工作,我可以读取通过浏览器返回的json并将其显​​示在我的angularjs视图中,但是单元测试无法正常工作。 错误是java.lang.AssertionError:预期状态:<200>,但之前是:<204>。 204-响应为空...可能是>正在初始化Spring FrameworkServlet”,即未初始化框架Servlet? 不确定。 任何帮助将不胜感激

我的休息总督

@RestController公共类ItemRestController {

@Autowired
ItemService catalogueService;  //Service which will do product retrieval

@Autowired
LocationService locationService;  //Service which will retrieve customer location id using customer id

//-------------------Retrieve All Customer Products--------------------------------------------------------

@RequestMapping(value = "/product/{customerId}", produces = {MediaType.APPLICATION_JSON_VALUE}, method = RequestMethod.GET)
public ResponseEntity<List<Product>> listCustomerProducts(@PathVariable("customerId") int customerId) {

    Integer customerLocation=(Integer) locationService.findLocationByCustomerId(customerId);
    List<Product> products = catalogueService.findCustomerProducts(customerLocation);

    if(products.isEmpty()){
        return new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<List<Product>>(products, HttpStatus.OK);
}

}

从堆栈跟踪中可以看到,测试由于断言错误而失败:它期望HTTP Status 200 ,但是得到204 ,即HTTPStatus.NO_CONTENT ,当列表为空时,您将在控制器中返回该状态。

        if(products.isEmpty()){
            return new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT);
        }

如果您想让控制器返回200,则需要CatalogueService模拟来返回某些内容。

在测试中,您正在ItemService (使用productServiceMock ),但是您的控制器正在调用CatalogueService实例。

还要确保正确注入了模拟,调试器确实是您最好的朋友。 我从您的语法猜测,您正在使用Mockito。 在这种情况下,模拟对象的getClass().getName()方法中具有“ $$ EnhancedByMockito”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM