今天学习了下,mybatis中开发dao的方法,用到了JUnit4进行单元测试,

将JUnit4中的注解总结了下,供大家参考学习:

JUnit 4 开始使用 Java 5 中的注解(annotation),常用的几个 annotation 介绍:

@BeforeClass:针对所有测试方法,只执行一次,且方法声明必须为static void

@Before:初始化方法(在测试方法之前执行)

@Test:测试方法,在这里可以进行具体的测试

@After:释放资源 (在测试方法之后执行)

@AfterClass:针对所有测试方法,只执行一次,且方法声明必须为static void

@Ignore:忽略的测试方法

一个单元测试用例执行顺序为: @BeforeClass –> (@Before –> @Test –> @After)...–> @AfterClass
其中每一个测试方法的调用顺序为: @Before –> @Test –> @After

如果只执行一个单元测试用例中的一个方法,则执行顺序为:@BeforeClass –> @Before –> @Test –> @After –> @AfterClass

测试类代码如下:

 package org.pine.mybatis.dao.impl;

 import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.pine.mybatis.dao.UserDao;
import org.pine.mybatis.po.User; public class UserDaoImplTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass
public static void initTest() throws IOException{
System.out.println("initTest");
String fileName ="SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(fileName);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} @AfterClass
public static void destoryTest(){
System.out.println("destoryTest");
} @Before
public void setUp() throws Exception {
System.out.println("setUp");
} @After
public void tearDown() throws Exception {
System.out.println("tearDown");
} @Ignore
@Test
public void testInsertUser() throws ParseException {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user = new User();
user.setUsername("武利丹");
user.setBirthday(new Date(new SimpleDateFormat("yyyy-MM-dd").parse("1990-06-18").getTime() ));
user.setSex("女");
user.setAddress("河南安阳");
userDao.insertUser(user);
} @Ignore
@Test
public void testGetUserById() {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
int id = 28;
User user= userDao.getUserById(id);
System.out.println(user);
} @Ignore
@Test
public void testUpdateUser() throws ParseException {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
User user = new User();
user.setId(36);
user.setUsername("孙坤鹏");
user.setBirthday(new Date(new SimpleDateFormat("yyyy-MM-dd").parse("1991-09-13").getTime()));
user.setSex("男");
user.setAddress("河南新乡12345~~~");
userDao.updateUser(user);
} @Test
public void testDeleteUser() {
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
Integer id = 40;
userDao.deleteUser(id);
} }
04-27 16:48