问答平台(8),单元测试

Spring Boot Testing

1
2
- 依赖:spring-boot-starter-test
- 包括:Junit、Spring Test、AssertJ、...

Test Case

1
2
3
- 要求:保证测试方法的独立性。
- 步骤:初始化数据、执行测试代码、验证测试结果、清理测试数据。
- 常用注解:@BeforeClass@AfterClass@Before@After

测试类

  • SpringBootTests: 新增
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ContextConfiguration(classes = CommunityApplication.class)
    public class SpringBootTests {

    @Autowired
    private DiscussPostService discussPostService;

    private DiscussPost data;

    @BeforeClass
    public static void beforeClass() {
    System.out.println("beforeClass");
    }

    @AfterClass
    public static void afterClass() {
    System.out.println("afterClass");
    }

    @Before
    public void before() {
    System.out.println("before");

    // 初始化测试数据
    data = new DiscussPost();
    data.setUserId(111);
    data.setTitle("Test title");
    data.setContent("Test content");
    data.setCreateTime(new Date());
    discussPostService.addDiscussPost(data);
    }

    @After
    public void after() {
    System.out.println("after");

    // 删除测试数据(拉黑帖子)
    discussPostService.updateStatus(data.getId(), 2);
    }

    @Test
    public void test1() {
    System.out.println("test1");
    }

    @Test
    public void test2() {
    System.out.println("test2");
    }

    @Test
    public void testFindById() {
    DiscussPost post = discussPostService.findDiscussPostById(data.getId());
    Assert.assertNotNull(post);
    Assert.assertEquals(data.getTitle(), post.getTitle());
    Assert.assertEquals(data.getContent(), post.getContent());
    }

    @Test
    public void testUpdateScore() {
    int rows = discussPostService.updateScore(data.getId(), 2000.00);
    Assert.assertEquals(1, rows);

    DiscussPost post = discussPostService.findDiscussPostById(data.getId());
    Assert.assertEquals(2000.00, post.getScore(), 2);
    }
    }

结果展示

单元测试-图示

参考资料


问答平台(8),单元测试
https://lcf163.github.io/2020/06/22/问答平台(8),单元测试/
作者
乘风的小站
发布于
2020年6月22日
许可协议