单元测试记录

背景:

系统进行大面积的重构,数据库的结构发生重大调整,然而每个人负责的模块都不同,但是有先后顺序,比如我负责的是公告管理模块,属于管理员的模块,但是登陆注册模块没有完成,所以只能从后台进行测试,于是单元测试必不可少。

可以使用的单元测试方法

之所以可以使用的是因为网上有好多的单元测试,第一次使用单元测试有可能使用不熟练。代码:

package cn.tj.user;

import cn.tj.entity.Notice;
import cn.tj.mapper.NoticeMapper;
import cn.tj.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;

/**
 * @Created by Intellij IDEA.
 * @author: 
 * @Date: 2020-04-24
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class NoticeTest {
    @Autowired
    private NoticeService noticeService;
    @Test
    public void testFindAll(){
        List<Notice> allNotice = noticeService.findAllNotice();
        System.out.println(allNotice);
        log.info("所有的公告:[{}]",allNotice);
    }
    @Test
    public void testAddNotice(){
        Notice notice = new Notice();
        notice.setNotiName("测试新增");
        notice.setNotiCreator("管理员");
        notice.setNotiContent("测试增加一条公告");
        notice.setNotiCreateTime(new Date());
        int i = noticeService.addNotice(notice);
        if (i == 1) {
            log.info("成功");
        }
    }
}

有可能发生的错误

JUnit测试提示Java.lang.Exception: No runnable methods: 没有加@Test注解

需要注意的问题

测试有专门测试的包,现在大部分都是springboot的,springboot自动生成test包,如果是别的,记得好像是要跟代码的目录结构必须一致。比如在src/main/java/cn/hh/service/noticeService,则需要在test里面按照这样创建。

idea下的自动创建单元测试

找到需要创建的单元测试方法,比如这里的deleteOneNotice方法

选中后右击,选择generate...

选择想要测试的方法:

一般使用JUnit4,比如选择最后三项。

package cn.tj.service;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * @Created by Intellij IDEA.
 * @author: 陈亚萌
 * @Date: 2020-04-24
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class NoticeServiceTest {

    @Test
    public void deleteOneNotice() {
        System.out.println(111);
    }

    @Test
    public void updateNotice() {
    }

    @Test
    public void selectNewlyNotice() {
    }
}

最后一种比较方便。最后,idea niubility

 posted on 2020-04-24 17:37  ben跑的换行符  阅读(316)  评论(0编辑  收藏  举报