使用Junit+Mockito完成单元测试

1、SpringBoot集成Junit5

我在测试中使用的SpringBoot版本为3.0.5,在SpringBoot3中引入Junit5只需要添加三个Junit5的三个依赖,并不需要指定版本号,SpringBoot已经为我们管理好了依赖的版本号。

<!--Junit5依赖-->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
</dependency>

2、SpringBoot集成Mockito

<!--Mockito依赖-->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <scope>test</scope>
</dependency>
<!--模拟静态方法所需要的依赖-->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <scope>test</scope>
</dependency>
<!--Mockito集成到Junit5-->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>

3、准备一个需要被测试的方法

我这里写了一个service,业务是对传入的学生对象验证生日信息是否正确,如果正确则为学生添加学号信息后存入数据库。

@Component
@Slf4j
public class StudentServiceImpl  implements StudentService {
    @Resource
    private StudentDao studentDao;

    @Override
    public void addStudent(Student student) {
        log.info("新增学生{}", student);
        // 校验数据
        if (student.getBirthday() == null) {
            throw new VerifyException("请输入学生生日");
        }
        if (!VerifyUtil.verifyIsDateFormat(student.getBirthday())) {
            throw new VerifyException("学生生日格式有误");
        }
        // 添加学号
        student.setStudentCode(CodeUtil.createCode());
        // 保存学生
        studentDao.insertStudent(student);
    }

}

1)工具类VerifyUtil和工具类CodeUtil

工具类VerifyUtil提供了对日期格式的验证

public class VerifyUtil {
    public static boolean verifyIsDateFormat(String str) {
        String timeRegex1 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|"+
                "((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|"+
                "((0[48]|[2468][048]|[3579][26])00))-02-29)$";

        return Pattern.matches(timeRegex1, str);
    }
}

工具类CodeUtil是生成一个学号,因为这里是测试用例,所以简略返回一个字符串"1001"

public class CodeUtil {
    public static String createCode() {
        return "1001";
    }
}

2)dao层实现

这里只对service层做测试,dao的实现细节就不做展示了,在测试中会使用@Mock注解对这个数据进行模拟,不去执行真实的方法。

4、单元测试

1)在需要被测试的service实现类上Alt+Enter,点击Create Test

2) 根据需要来配置单元测试类

这些都可以在测试类创建完成后修改

3)写测试方法

// 使用了这个注解开启mock能力
@ExtendWith(MockitoExtension.class)
class StudentServiceImplTest {

    // 实例化一个模拟的类,@Mock和@Spy注解模拟的类都会被注入到这个类中
    @InjectMocks
    StudentServiceImpl service;

    // 模拟一个类,不会去执行真实方法
    @Mock
    StudentDao studentDao;


    /**
     * 在所有测试方法之前执行的方法
     */
    @BeforeAll
    static void doBefore() {
        System.out.println("开始测试");
    }

    /**
     * 在所有测试方法之后执行的方法
     */
    @AfterAll
    static void doAfter() {
        System.out.println("结束测试");
    }

    /**
     * 测试方法
     */
    @Test
    void addTest() {
        Student student = new Student();
        // 学生生日为空
        try {
            service.addStudent(student);
            Assertions.fail();
        }catch (VerifyException e) {
            Assertions.assertEquals("请输入学生生日", e.getMessage());
        }

        // 学生生日格式有误
        student.setBirthday("123");
        try {
            service.addStudent(student);
            Assertions.fail();
        }catch (VerifyException e) {
            Assertions.assertEquals("学生生日格式有误", e.getMessage());
        }

        // 打桩 如果调用了createCode()方法则返回固定的"1002"
        Mockito.mockStatic(CodeUtil.class).when(CodeUtil::createCode).thenReturn("1002");

        // 正确的数据
        student.setBirthday("2000-03-21");
        service.addStudent(student);

    }

}

 5、测试结果

测试通过,行覆盖率为100%

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于构建Java应用程序的开源框架,它提供了一种简化了配置的方式来快速构建应用程序。JUnit是一个用于编写和运行单元测试的开源测试框架,而Mockito是一个用于创建和管理模拟对象的Java库。 下面是一个使用Spring Boot、JUnitMockito进行单元测试的示例: 假设我们有一个UserService类,它依赖于一个UserRepository接口来访问数据库并进行一些操作。我们想要对UserService的方法进行单元测试。 首先,我们需要创建一个测试类,命名为UserServiceTest。在测试类中,我们将使用JUnit的注解来标记测试方法,并使用Mockito来创建模拟对象。示例代码如下: ```java @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @InjectMocks private UserService userService; @Mock private UserRepository userRepository; @Test public void testGetUserById() { // 配置模拟对象的行为 User user = new User("1", "John"); when(userRepository.findById("1")).thenReturn(user); // 调用被测试的方法 User result = userService.getUserById("1"); // 验证结果 assertEquals("John", result.getName()); } } ``` 在上面的示例中,我们使用了@RunWith注解来指定使用MockitoJUnitRunner运行测试,这样就能自动创建和管理模拟对象。使用@InjectMocks注解将被测试的对象自动注入到测试类中,使用@Mock注解创建模拟对象。 在testGetUserById方法中,我们首先使用when方法配置userRepository模拟对象的行为,表示当传入参数为"1"时,返回一个指定的User对象。 然后,我们通过调用userService的getUserById方法来测试该方法的逻辑。最后,使用assertEquals断言来验证结果是否符合预期。 以上就是一个使用Spring Boot、JUnitMockito进行单元测试的示例。通过使用Mockito创建模拟对象,我们可以更容易地测试各个方法的逻辑,而不依赖于实际的数据库。这样可以提高测试效率并确保代码的质量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值