1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
自定义控制资源,默认情况下资源文件变化不会触发重启,可以通过配置更改:
spring.devtools.restart.exclude = static/*
或者方向配置需要监控的目录,发现变化时自动重启项目:
spring.devtools.restart.additional-paths=src/main/resources/static
或者可以使用LiveReload而不是重启项目的方式,因为重启项目会比较耗时
2.使用单元测试
创建项目后,自动生成一个测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {
@Test
public void contextLoads() {
}
}
service测试
创建service:
@Service
public class TestService {
public String sayHellow(){
return "hello";
}
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {
// private static Logger logger = LoggerFactory.getLogger("bifan");
@Autowired
TestService service;
@Test
public void contextLoads() {
String testStr = service.sayHellow();
Assert.assertThat(testStr, Matchers.is("hello"));
}
}
controller测试
需要用到Mock测试,因为不易获取的对象,需要采用虚拟的对象来创建进行测试。
创建controller:
@RestController
public class TestController {
@Autowired
UserMapper userMapper;
@GetMapping("/test")
public List<Userinfo> test() {
return userMapper.findAll();
}
}
创建测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {
@Autowired
WebApplicationContext webApplicationContext;
MockMvc mockMvc;
@Before
public void before(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void contextLoads() throws Exception{
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/test")
.contentType(MediaType.APPLICATION_FORM_URLENCODED))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
}
打印结果: