Spring Boot RestEasy Post方法预期:201实际:404

时间:2017-11-03 23:44:23

标签: java spring unit-testing spring-boot resteasy

我有一个spring boot应用程序,其中包含使用@Service创建的RestEasy Web服务,如:

@Path("/developers")
@Service
public interface DeveloperResource {
@POST
@Produces("application/json")
@Consumes("application/json")
Response create(@RequestBody List<DeveloperDto> developers);
}

我有相应的集成测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class DeveloperResourceTest {

    public static final String URI = "http://localhost:8080/developers";
    public static final DeveloperDto DEVELOPER = new DeveloperDto(null, "toto");
    public static final List<DeveloperDto> DEVELOPERS_COLLECTION = Collections.singletonList(DEVELOPER);
    public static final DeveloperEntity DEVELOPER_MAPPED_TO_ENTITY = DeveloperMapper.toEntity(DEVELOPER);
    public static final String DEVELOPER_COLLECTION_IN_JSON = "[{\"developerId\":null,\"developerName\":\"toto\",\"programmingLanguages\":null}]";


    private MockMvc mockMvc;

    @MockBean
    DeveloperService service;

    @Mock
    private DeveloperResource tested;

    @Autowired
    WebApplicationContext webApplicationContext;

    private ObjectMapper mapperJson;

    @Before
    public void setUp() throws Exception {
        tested=new DeveloperResourceImpl(service);
        mockMvc=MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
        mapperJson = new ObjectMapper();
    }

    @Test
    public void should_create_a_developer_and_return_OK() throws Exception {
        Mockito.when(service.save(DEVELOPER_MAPPED_TO_ENTITY)).thenReturn(Optional.of(DEVELOPER_MAPPED_TO_ENTITY));

        tested.create(DEVELOPERS_COLLECTION);

        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .post(URI)
                .content(DEVELOPER_COLLECTION_IN_JSON)
                .contentType(MediaType.APPLICATION_JSON);

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

        MockHttpServletResponse response = result.getResponse();

        assertEquals(HttpStatus.CREATED.value(), response.getStatus());
        assertEquals(URI, response.getHeader(HttpHeaders.LOCATION));

    }
}

执行测试后我得到了:

  

java.lang.AssertionError:   预计:201   实际:404

我的问题是:

  1. 我的集成测试配置是否合适?
  2. 即使创建的REST Web服务没有使用@RestController或@Controller创建,我们也能使用MockMvc吗?
  3. 提前谢谢

2 个答案:

答案 0 :(得分:0)

@Service不会被识别为休息服务。你应该在类上注释它为@RestController,实际上是实现了create方法。 见:@Service

答案 1 :(得分:0)

您无法使用MockMvc来测试不使用Spring MVC的应用。 RESTdocs支持Rest Assured,它可以通过HTTP工作,因此它不依赖于Web堆栈。