【发布时间】:2018-04-16 18:44:18
【问题描述】:
我有一个 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
我的问题是:
- 我的集成测试配置合适吗?
- 即使创建的 REST Web 服务不是使用 @RestController 或 @Controller 创建的,我们也可以使用 MockMvc 吗?
提前谢谢你
【问题讨论】:
-
你能发布你的 application.properties 吗?
-
感谢您的回复,我没有用于配置的属性文件,因为它是使用 Spring Boot 自动配置:“@SpringBootApplication”“@ComponentScan”我有 application.yaml,但它只包含持久化配置:服务器端口:8080 jpa hibernate auto database URL
标签: java spring unit-testing spring-boot resteasy