Spring-boot version application-test.yml
;
../src/test/resources
档案位置:spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:test;MODE=MySQL
profiles:
active: test
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = RestApiConfiguration.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@ActiveProfiles("test")
public class BaseRestApiTest {
@Autowired
protected TestRestTemplate restTemplate;
}
我的测试BaseClass是:
BaseRestApiTest
现在在扩展http://127.0.0.1:8080/api/user/create
的测试类中,我将数据发布到@Test
public void testAdd() {
String url = HOST + "/api/user/create";
Map<String, Object> form = Maps.newHashMap();
form.put("userId", 1);
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(form.size());
params.setAll(form);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, httpHeaders);
ResponseEntity<Long> resp = restTemplate.exchange(url, HttpMethod.POST, entity, Long.class);
Assert.assertNotNull(resp.getBody());
}
之类的URL,最后,用户数据被写入我的本地MySQL数据库。
H2
期望用户数据只是写在内存中的setenv.bat
,而不是我本地的MYSQL数据库。
答案 0 :(得分:1)
您的BaseRestApiTest已标记为@ActiveProfiles(“test”),因此您需要在application-test.yml中拥有以下内容:
spring:
jpa:
database: HSQL
和依赖关系,如本示例中所示,我使用了Gradle,因此它遵循以下行:
testCompile group: 'org.hsqldb', name: 'hsqldb'
ofc,如果您使用的是maven,则需要在pom.xml文件中以maven格式编写它。