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 菴ソ逕ィ譁ケ豕/繝繧ケ繝亥ョ溯。縲榊盾辣ァ

Follow me!