2017-11-03 60 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棧。