单元测试

@Before和@BeforeClass的区别:

  • @Before是每个测试方法之前都需要调用

  • @BeforeClass是整个单元测试之前调用,被@BeforeClass修饰的方法必须是静态的

无主外键关系时,都可用如下方法:

 1     static Logger logger = LogManager.getLogger(CollegeMapperTest.class);
 2 
 3     @BeforeClass
 4     public static void setUp() throws Exception {
 5         logger.info("before College ●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●");
 6         SqlSession session = Dbutil.getSession();
 7         if (session != null) {
 8             CollegeMapper mapper = session.getMapper(CollegeMapper.class);
 9             mapper.deleteAll();
10             session.commit();
11             session.close();
12         }
13     }
14 
15     @AfterClass
16     public static void tearDown() throws Exception {
17         logger.info("after College ●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●");
18         SqlSession session = Dbutil.getSession();
19         if (session != null) {
20             CollegeMapper mapper = session.getMapper(CollegeMapper.class);
21             mapper.deleteAll();
22             College college = new College();
23             college.setcollegeId(1);
24             college.setcollegeName("太原工业学院");
25             mapper.insert(college);
26             session.commit();
27             session.close();
28         }
29     }

若有主外键关系,新建一个allTest类:

 1 @RunWith(Suite.class)
 2 @Suite.SuiteClasses({
 3         CollegeMapperTest.class,
 4         MajorMapperTest.class,
 5         ClazzMapperTest.class
 6 })
 7 public class AllTest {
 8     private static Logger logger = LogManager.getLogger(AllTest.class);
 9 
10     @BeforeClass
11     public static void before() {
12         logger.info("allTest before ●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●");
13         SqlSession session = Dbutil.getSession();
14         if (session != null) {
15             ClazzMapper clazzMapper = session.getMapper(ClazzMapper.class);
16             clazzMapper.deleteAll();
17             MajorMapper majorMapper = session.getMapper(MajorMapper.class);
18             majorMapper.deleteAll();
19             CollegeMapper collegeMapper = session.getMapper(CollegeMapper.class);
20             collegeMapper.deleteAll();
21             session.commit();
22             session.close();
23         }
24     }
25 
26     @AfterClass
27     public static void after() {
28         logger.info("after allTest ●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●■◆●");
29     }
30 
31 }

测试规范:

在整个的单元测试类中,可以将方法命名为test1,test2,test3.。。。。。

junit会自动的按照命名顺序执行

断言:

  • 集合,对象类型:(查询)
    1 Major major = mapper.selectById(id);
    2 Assert.assertNotNull(major);
  • int类型:(增删改)
    1 int result = mapper.update(major);
    2 Assert.assertEquals(1, result);

     

避免主键冲突

  1.  测试时可以先将表中数据(测试表)全部删掉,每次单元测试之前将表清空,退出单元测试之前也进行清空

 

posted @ 2020-08-12 11:52  玖捌贰陆  阅读(104)  评论(0编辑  收藏  举报