1

Spring-boot version 1.5.3.RELEASE;

application-test.yml file location: ../src/test/resources

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:test;MODE=MySQL
  profiles:
    active: test

and my test BaseClass is:

@RunWith(SpringRunner.class)
@SpringBootTest(
        classes = RestApiConfiguration.class,
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@ActiveProfiles("test")
public class BaseRestApiTest {

    @Autowired
    protected TestRestTemplate restTemplate;

}

and now in the test class which extends BaseRestApiTest, I post data to an URL like http://127.0.0.1:8080/api/user/create, and finally, the user data was written to my local MySQL DB.

@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());
    }

Expecting is the user data was just written in H2 in the memory, but not my local MYSQL DB.

4

1 回答 1

1

您的 BaseRestApiTest 已经用 @ActiveProfiles("test") 进行了标记,因此您在 application-test.yml 中需要的内容如下:

spring:
jpa:
    database: HSQL

和一个依赖项,就像在这个示例中一样,我使用了 Gradle,所以它是以下行:

    testCompile group: 'org.hsqldb', name: 'hsqldb'

ofc,如果你使用的是 maven,你需要在你的 pom.xml 文件中以 maven 格式编写它。

于 2017-07-11T13:24:21.117 回答