Spring Boot 8 テスト

設定

pom.xml
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-test</artifactId>
 <scope>test</scope>
</dependency>

テスト対象

Bean

※MyBean.java
public class MyBean {
 public String getTest1(){
  return "TEST1";
 }
 public String getTest2(){
  return "TEST2";
 }
}

※MyAppConfig.java
@Configuration
public class MyAppConfig {
 @Bean
 public MyBean getMyBean(){
  return new MyBean();
 }
}

コントローラ

※HelloController.java
@Controller
public class HelloController {
 @Autowired
 MyBean bean;

 @RequestMapping(value = "/")
 public ModelAndView index(ModelAndView model){
  model.setViewName("index");
  model.addObject("test", bean.getTest1() + bean.getTest2());
  return model;
 }
}

RESTコントローラ

※HelloRestController
@RestController
public class HelloRestController {
 @Autowired
 MyBean bean;

 @RequestMapping(value = "/rest/")
 public String index(ModelAndView model){
  return bean.getTest1() + bean.getTest2();
 }
}

テストコード

Bean

※MyBeanTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MyBeanTest {
 @Autowired
 MyBean bean;

 @Test
 public void testGet(){
  assertEquals("test", bean.test());
 }
}

コントローラ

※ControllerTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
 @Autowired
 private MockMvc mock;

 @Autowired
 MyBean bean;

 @Test
 public void indexOK() throws Exception{
  mock.perform(get("/"))
   .andExpect(status().isOk())
   .andExpect(view().name("index"))
   .andExpect(model().hasNoErrors());
 }
}

RESTコントローラ

※ControllerTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
 @Autowired
 private MockMvc mock;

 @Autowired
 MyBean bean;

 @Test
 public void restOK() throws Exception{
  mock.perform(get("/rest/"))
   .andExpect(status().isOk());
 }
}

実行

Eclipse
自動テストツール JUnit」参照

Maven
Apache Maven 使用方法/テスト実行」参照