spring.datasource.url = jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE;
spring.datasource.username = sa
spring.datasource.password =
テスト時に使用するテストデータを用意する
src/test/resources/import.sql
sql
1INSERTINTO memo (id, title, description, done, updated)VALUES(1001,'H2 Test title 1001','H2 Test description 1001',false,'2020-01-01');2INSERTINTO memo (id, title, description, done, updated)VALUES(1002,'H2 Test title 1002','H2 Test description 1002',false,'2020-02-02');3INSERTINTO memo (id, title, description, done, updated)VALUES(1003,'H2 Test title 1003','H2 Test description 1003',false,'2020-03-03');4INSERTINTO memo (id, title, description, done, updated)VALUES(1004,'H2 Test title 1004','H2 Test description 1004',false,'2020-04-04');5INSERTINTO memo (id, title, description, done, updated)VALUES(1005,'H2 Test title 1005','H2 Test description 1005',false,'2020-05-05');
コントローラーのテストコード
テスト時にデータベースアクセスが行われますが、H2を利用するため実行環境を選びません。
java
1importcom.example.demo.model.Memo;2importorg.junit.Test;3importorg.junit.runner.RunWith;4importorg.springframework.beans.factory.annotation.Autowired;5importorg.springframework.boot.test.context.SpringBootTest;6importorg.springframework.boot.test.web.client.TestRestTemplate;7importorg.springframework.http.HttpStatus;8importorg.springframework.http.MediaType;9importorg.springframework.http.ResponseEntity;10importorg.springframework.test.context.TestPropertySource;11importorg.springframework.test.context.junit4.SpringRunner;1213importstaticorg.assertj.core.api.Assertions.assertThat;1415@RunWith(SpringRunner.class)16@SpringBootTest(webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)17@TestPropertySource(locations ="/application.test.properties")18publicclassMemoControllerIntegrationTests{1920@Autowired21privateTestRestTemplate testRestTemplate;2223@Test24publicvoidgetMemo(){25ResponseEntity<Memo> result = testRestTemplate.getForEntity("/memo/1001",Memo.class);2627assertThat(result).isNotNull();28assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);29assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8);30assertThat(result.getBody().getId()).isEqualTo(1001L);31}3233@Test34publicvoidgetMemos(){35ResponseEntity<Memo[]> result = testRestTemplate.getForEntity("/memo/all",Memo[].class);3637assertThat(result).isNotNull();38assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK);39assertThat(result.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON_UTF8);40assertThat(result.getBody()).hasSize(5);41}4243}
2) リポジトリをモック化するが、単体テストとして実装する
特徴
単体テストとして実装する。
リポジトリをモック化する。
データベースアクセスは行わない。
コントローラーのテストコード
テスト時にリポジトリをモック化するのでデータベースアクセスは行われません。
java
1importcom.example.demo.model.Memo;2importcom.example.demo.repository.MemoRepository;3importcom.example.demo.service.impl.MemoServiceImpl;4importcom.fasterxml.jackson.databind.ObjectMapper;5importorg.junit.Test;6importorg.junit.runner.RunWith;7importorg.mockito.Mockito;8importorg.springframework.beans.factory.annotation.Autowired;9importorg.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;10importorg.springframework.boot.test.mock.mockito.MockBean;11importorg.springframework.boot.test.mock.mockito.SpyBean;12importorg.springframework.http.MediaType;13importorg.springframework.test.context.junit4.SpringRunner;14importorg.springframework.test.web.servlet.MockMvc;15importorg.springframework.test.web.servlet.MvcResult;16importorg.springframework.test.web.servlet.RequestBuilder;17importorg.springframework.test.web.servlet.request.MockMvcRequestBuilders;1819importjava.nio.charset.StandardCharsets;20importjava.util.Arrays;21importjava.util.List;22importjava.util.Optional;2324importstaticorg.assertj.core.api.Assertions.assertThat;25importstaticorg.mockito.ArgumentMatchers.anyLong;2627importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.content;28importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;2930@RunWith(SpringRunner.class)31@WebMvcTest(MemoController.class)32publicclassMemoControllerTests{3334@Autowired35privateMockMvc mvc;36@Autowired37privateObjectMapper objectMapper;3839@MockBean40privateMemoRepository memoRepository;4142@SpyBean43privateMemoServiceImpl memoService;4445privateMediaType contentType =newMediaType(MediaType.APPLICATION_JSON.getType(),46MediaType.APPLICATION_JSON.getSubtype(),StandardCharsets.UTF_8);4748@Test49publicvoidgetMemo()throwsException{50Memo expected =Memo.of(1L,"test title","test description");51Mockito.when(memoRepository.findById(anyLong())).thenReturn(Optional.ofNullable(expected));5253RequestBuilder builder =MockMvcRequestBuilders.get("/memo/{id}",1L)54.accept(MediaType.APPLICATION_JSON_UTF8);5556MvcResult result = mvc.perform(builder)57.andExpect(status().isOk())58.andExpect(content().contentType(contentType))59.andReturn();6061String expectedJson = objectMapper.writeValueAsString(expected);62assertThat(result.getResponse().getContentAsString()).isEqualTo(expectedJson);63}6465@Test66publicvoidgetMemos()throwsException{67List<Memo> expected =Arrays.asList(68Memo.of(1L,"test title 1","test description 1"),69Memo.of(2L,"test title 2","test description 2"),70Memo.of(3L,"test title 3","test description 3")71);72Mockito.when(memoRepository.findAll()).thenReturn(expected);7374RequestBuilder builder =MockMvcRequestBuilders.get("/memo/all")75.accept(MediaType.APPLICATION_JSON_UTF8);7677MvcResult result = mvc.perform(builder)78.andExpect(status().isOk())79.andExpect(content().contentType(contentType))80.andReturn();8182String expectedJson = objectMapper.writeValueAsString(expected);83assertThat(result.getResponse().getContentAsString()).isEqualTo(expectedJson);84}85}