java.lang.AssertionError:期望的状态:< 200>但是:< 404>

时间:2015-08-05 05:09:45

标签: java rest spring-mvc junit mockito

我有一个像

这样的控制器类
package com.lsy.lido.lcb.services.web;


/**
 * Controller class to retrieve, create, update and delete customer.
 * 
 */
@Controller
@RequestMapping("/customers")
public class CustomerController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    CustomerService customerService;

    @Produce(uri = "direct:defaultEndPoint")
    private ProducerTemplate template;

    /**
     * Method to retrieve the list of customer from Database
     * 
     * @return - List of all customers
     */
    @ResponseBody
    @RequestMapping(value = "/", method = RequestMethod.GET, produces = { ContentType.JSON, ContentType.XML })
    public CustomersDTO getCustomers() {
        LOGGER.info("Inside customers");
        CustomersDTO customers = customerService.getAllCustomers();
        CustomersDTO linkedCustomers = new CustomersDTO();
        for (CustomerDTO cust : customers.getCustomersList()) {
            linkedCustomers.getCustomersList().add(EntityResourceSupport.addLinksToCustomer(cust, LinkType.SELF));
            template.asyncSendBody(template.getDefaultEndpoint(), cust.getFirstName());
        }

        return linkedCustomers;
    }


}

我需要写同样的junit。 我写过junit,如:

package com.lsy.lido.lcb.services;


@RunWith(SpringJUnit4ClassRunner.class)
/*
 * @ContextConfiguration(locations = {
 * "classpath*:spring/application-context.xml" })
 */
@ContextConfiguration(classes = { TestContext.class })
@WebAppConfiguration
public class CustomerControllerTest {
    private MockMvc mockMvc;

    @Autowired
    private CustomerService todoServiceMock;
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        Mockito.reset(todoServiceMock);

        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                .build();

    }

    @Test
    public void findAll() throws Exception {
        CustomerDTO first = new CustomerDTO("1", "Test1", "User1");
        CustomerDTO second = new CustomerDTO("2", "Test2", "User2");
        CustomersDTO dto = new CustomersDTO();
        dto.setCustomersList(Arrays.asList(first, second));
        when(todoServiceMock.getAllCustomers()).thenReturn(dto);
        mockMvc.perform(get("/customers/"))
                .andExpect(status().isOk())
                .andExpect(
                        content().contentType(TestUtil.APPLICATION_JSON_UTF8))
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].customerId", is(1)))
                .andExpect(jsonPath("$[0].firstName", is("Test1")))
                .andExpect(jsonPath("$[0].lastName", is("User1")))
                .andExpect(jsonPath("$[1].customerId", is(2)))
                .andExpect(jsonPath("$[1].firstName", is("Test2")))
                .andExpect(jsonPath("$[1].lastName", is("User2")));

        verify(todoServiceMock, times(1)).getAllCustomers();
        verifyNoMoreInteractions(todoServiceMock);

    }

}

我的上下文类是:

package com.lsy.lido.service.config;   


@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 CustomerService todoService() {
        return Mockito.mock(CustomerService.class);
    }
    @Bean
    public CustomerRepository todoServiceRepo() {
        return Mockito.mock(CustomerRepository.class);
    }

    @Bean
    public GridFsTemplate gridFsTemplate() {
        return Mockito.mock(GridFsTemplate.class);
    }
    @Bean
    public MongoTemplate mongoTemplate() {
        return Mockito.mock(MongoTemplate.class);
    }
}

但是当我运行测试用例时,我收到以下错误: 堆栈跟踪:

java.lang.AssertionError: Status expected:<200> but was:<404>
    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$10.match(StatusResultMatchers.java:653)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
    at com.lsy.lido.lcb.services.CustomerControllerTest.findAll(CustomerControllerTest.java:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

请帮我解决一下我的情况下缺少什么配置?

0 个答案:

没有答案