模拟MVC意外结果

时间:2015-07-26 01:32:33

标签: java spring web-services rest junit

我正在测试这个控制器:

 package hello;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;

@RestController
public class OfficeRestController {

    @Autowired
    private OfficeRepository officeRepository;
    private HashMap<String, String> readingProblems = new HashMap<>();

    @RequestMapping(value = "/office/{id}", method = RequestMethod.GET)
    ResponseEntity<Office> readOfficeDetails(@PathVariable long id) {
        HttpStatus status = HttpStatus.OK;      
        if (officeRepository.findOne(id) == null)
            status = HttpStatus.NOT_FOUND;

        return new ResponseEntity<Office>(officeRepository.findOne(id), status);
    }

    @RequestMapping(value = "/offices", method = RequestMethod.GET)
    ResponseEntity<Collection<Office>> allOffices() {
        HttpStatus status = HttpStatus.OK;
        Collection<Office> ans = this.officeRepository.findAll();
        if (ans.size() == 0)
            status = HttpStatus.NOT_FOUND;

        return new ResponseEntity<Collection<Office>>(
                this.officeRepository.findAll(), status);
    }

    @RequestMapping(value = "/openOffices", method = RequestMethod.GET)
    ResponseEntity<Collection<Office>> openOffices() {
        HttpStatus status = HttpStatus.OK;
        boolean found = false;
        Collection<Office> ans = new ArrayList<Office>();
        for (Office office : officeRepository.findAll()) {
            LocalTime curTime = LocalTime.now();
            LocalTime opening = office.getOpenFrom();
            LocalTime closing = office.getOpenUntil();
            if ((curTime.compareTo(opening) == 0 || curTime.compareTo(opening) == 1)
                    && (curTime.compareTo(closing) == 0 || curTime
                            .compareTo(closing) == -1)) {
                found = true;
                ans.add(office);
            }
        }
        if (!found) {
            status = HttpStatus.NOT_FOUND;
        }
        return new ResponseEntity<Collection<Office>>(ans, status);
    }

    @RequestMapping(value = "/offices", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    public ResponseEntity<Office> add(@RequestBody Office offices) {
        HttpStatus status = HttpStatus.CREATED;
        Office office = createNewOffice(offices);
        if (Office.regProblems.size() > 0) {
            status = HttpStatus.UNPROCESSABLE_ENTITY;
        }
        officeRepository.save(office);
        return new ResponseEntity<Office>(office, status);
    }

    public Office createNewOffice(Office officeObject) {
        Office office = new Office();
        office.setName(officeObject.getName());
        office.setLocation(officeObject.getLocation());
        office.setOpenFrom(officeObject.getOpenFrom().toString());
        office.setOpenUntil(officeObject.getOpenUntil().toString());
        office.setTimeDifference(officeObject.getTimeDifference().toString());
        return office;
    }

}

通过这个测试:

 package test;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import hello.Application;
import hello.Office;
import hello.OfficeRepository;
import hello.OfficeRestController;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class OfficeRestControllerTest {

    private MediaType contentType = new MediaType(
            MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("UTF8"));

    private MockMvc mockMvc;

    private OfficeRestController officeRestController = new OfficeRestController();

    private HttpMessageConverter mappingJackson2HttpMessageConverter;

    private Office account;

    @Autowired
    private OfficeRepository officeRepository;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    void setConverters(HttpMessageConverter<?>[] converters) {

        this.mappingJackson2HttpMessageConverter = Arrays
                .asList(converters)
                .stream()
                .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
                .findAny().get();

        Assert.assertNotNull("the JSON message converter must not be null",
                this.mappingJackson2HttpMessageConverter);
    }

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
        this.officeRepository.deleteAllInBatch();
        Office office = new Office();
        office.setName("Baku");
        office.setLocation("Azerbaijan");
        office.setOpenFrom("00:00");
        office.setOpenUntil("23:00");
        office.setTimeDifference("3");
        this.officeRepository.save(office);
    }

    @Test
    public void officeNotFound() throws Exception {
        mockMvc.perform(get("/office/2")).andExpect(status().isNotFound())
                .andReturn();
    }

    @Test
    public void officeFound() throws Exception {
        mockMvc.perform(get("/office/1")).andExpect(status().isOk())
                .andExpect(content().contentType(contentType));

    }

    @Test
    public void seeOpenOffices() throws Exception {
        mockMvc.perform(get("/openOffices")).andExpect(status().isOk())
                .andExpect(content().contentType(contentType));

    }

    protected String json(Object o) throws IOException {
        MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage();
        this.mappingJackson2HttpMessageConverter.write(o,
                MediaType.APPLICATION_JSON, mockHttpOutputMessage);
        return mockHttpOutputMessage.getBodyAsString();
    }

}

结果是:

  

java.lang.AssertionError:期望的状态:&lt; 200&gt;但是:&lt; 404&gt;       在org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)       在org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)       在org.springframework.test.web.servlet.result.StatusResultMatchers $ 10.match(StatusResultMatchers.java:653)       在org.springframework.test.web.servlet.MockMvc $ 1.andExpect(MockMvc.java:152)       at test.OfficeRestControllerTest.officeFound(OfficeRestControllerTest.java:97)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)       at java.lang.reflect.Method.invoke(Unknown Source)       在org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:50)       在org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)       在org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)       在org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)       在org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)       在org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)       在org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)       在org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)       在org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)       在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290)       在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)       在org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)       在org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)       在org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)       在org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)       在org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)       在org.junit.runners.ParentRunner.run(ParentRunner.java:363)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)       在org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)       在org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)       在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)       在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)       在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)       在org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

但是有id=1条目。为什么结果是错的?

0 个答案:

没有答案