SpringBoot学习笔记(9)-使用Junit单元测试

文章目录

      • 一、build.grade
      • 二、主要注解
      • 三、编写单元测试
      • 补充:Test的starter


在使用SpringBoot的开发过程中,我们常常需要对一些模块进行单元测试,一方面可以让我们检查程序是否正确,另一方面也有利于我们了解模块运行打造的时间,让我们更好地去优化程序。

更多关于SpringBoot的总结请点击:SpringBoot使用总结


环境:IntelliJ Idea+Gradle4.8+SpringBoot2.0+Junit4


一、build.grade

//单元测试
	testCompile('org.springframework.boot:spring-boot-starter-test')

一般SpringBoot项目都会默认导入这个测试依赖,里边包含了Junit单元测试所需的Jar包


二、主要注解

//Junit4运行环境
@RunWith(SpringJUnit4ClassRunner.class)
//单元测试时需要执行的SpringBoot启动类
@SpringBootTest(classes = SpringbootMybatis2Application.class)
//webapp相关配置
@WebAppConfiguration
//单元测试的方法
@Test

注意,在SpringBoot2.0中,@SpringBootTest注解代替*@SpringApplicationConfiguration**注解*


三、编写单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootMybatis2Application.class)
@WebAppConfiguration
public class SpringBootTest {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Test
    public void fun1(){
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String value = ops.get("hello");
        System.out.println(value);
    }

    @Test
    public void fun2(){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameNotEqualTo("arong");
        List<User> users = userMapper.selectByExample(userExample);
        for (User user : users) {
            System.out.println(user.getUsername());
        }

    }

}

执行即可看到Junit测试生效
SpringBoot学习笔记(9)-使用Junit单元测试_第1张图片

补充:Test的starter

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

你可能感兴趣的:(#,ARong's,Java,Notes)