Reputation: 361
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.
Upvotes: 1
Views: 335
Reputation: 1346
Your BaseRestApiTest is already marked with @ActiveProfiles("test"), so all you need to have in your application-test.yml is following:
spring:
jpa:
database: HSQL
and of a dependency, as in this sample, I used Gradle, so it is following line:
testCompile group: 'org.hsqldb', name: 'hsqldb'
ofc, if you are using maven, you need to write it in maven format in your pom.xml file.
Upvotes: 1