我有包含使用@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