我有一个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
我的问题是:
提前谢谢
答案 0 :(得分:0)
@Service不会被识别为休息服务。你应该在类上注释它为@RestController,实际上是实现了create方法。 见:@Service
答案 1 :(得分:0)
您无法使用MockMvc
来测试不使用Spring MVC的应用。 RESTdocs支持Rest Assured,它可以通过HTTP工作,因此它不依赖于Web堆栈。