JavaWeb(SpringBoot3+vue3)开发+教学管理系统项目实战之JUnit单元测试断言
断言方法 | 描述 | Assertions.assertEquals(Object exp, Object act, String msg) | 检查两个值是否相等,不相等就报错。 | Assertions.assertNotEquals(Object unexp, Object act, String msg) | 检查两个值是否不相等,相等就报错。 | Assertions.assertNull(Object act, String msg) | 检查对象是否为null,不为null,就报错。 | Assertions.assertNotNull(Object act, String msg) | 检查对象是否不为null,为null,就报错。 | Assertions.assertTrue(boolean condition, String msg) | 检查条件是否为true,不为true,就报错。 | Assertions.assertFalse(boolean condition, String msg) | 检查条件是否为false,不为false,就报错。 | Assertions. assertThrows(Class expType, Executable exec, String msg) | 检查程序运行抛出的异常,是否符合预期。ceshse |
测试类代码如下:
- package com.jinhei;
-
- import org.junit.jupiter.api.Assertions;
- import org.junit.jupiter.api.Test;
-
- /**
- * 测试类
- */
- public class UserServiceTest {
- @Test
- public void testGetAge() {
- UserService userService = new UserService();
- Integer age = userService.getAge("110");
- System.out.println(age);
- }
- @Test
- public void testGetGender() {
- UserService userService = new UserService();
- String sex = userService.getGender("110101199801011234");
- System.out.println(sex);
- }
- @Test
- public void testGetAge2() {
- UserService userService = new UserService();
- Integer age = userService.getAge("110101199801011234");
- // 断言,第一个参数是预期值,第二个参数是实际值
- Assertions.assertEquals(38, age, "年龄计算错误");
- }
- @Test
- public void testGetGender2() {
- UserService userService = new UserService();
- String sex = userService.getGender("110101199801011234");
- // 断言, 第一个参数是预期值,第二个参数是实际值
- Assertions.assertEquals("女", sex, "性别计算错误");
- }
- @Test
- public void testGenderWithAssert() {
- UserService userService = new UserService();
- // 断言, 第一个参数是异常类,第二个参数是断言的代码块
- Assertions.assertThrows(IllegalArgumentException.class, () -> {
- userService.getGender(null);
- });
- }
- }
复制代码 完整代码:
demo01.zip
(8.05 KB, 下载次数: 0, 售价: 9 金币)
|