2017-11-03 61 views
0

我有包含使用@Service像创建的web服务RestEasy的弹簧引导应用:弹簧引导RestEasy的Post方法预期:201实测值:404

@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: Expected :201 Actual :404

我的问题是:

  1. 我的集成测试配置是否合适?
  2. 即使创建的REST Web服务不是使用@RestController或@Controller创建的,我们是否可以使用MockMvc ?.

预先感谢您

+0

你可以发布你的application.properties? – DeadSpock

+0

感谢的的答复,我没有一个属性文件的配置,因为它是利用弹簧开机自动配置: “@SpringBootApplication” “@ComponentScan” 我有application.yaml但它仅含有持久性配置: 服务器端口:8080 jpa hibernate auto 数据库URL – essalprod

回答

0

@服务将不会被识别为一个休息的服务。你应该在类上注释它为@RestController,实际上实现了create方法。 请参阅:@Service

0

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