我有包含使用@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
我的問題是:
- 我的集成測試配置是否合適?
- 即使創建的REST Web服務不是使用@RestController或@Controller創建的,我們是否可以使用MockMvc ?.
預先感謝您
你可以發佈你的application.properties? – DeadSpock
感謝的的答覆,我沒有一個屬性文件的配置,因爲它是利用彈簧開機自動配置: 「@SpringBootApplication」 「@ComponentScan」 我有application.yaml但它僅含有持久性配置: 服務器端口:8080 jpa hibernate auto 數據庫URL – essalprod