通过对@Test 传入expected 参数值,即可测试异常。
通过传入异常测试类以后,测试类如果没有抛出异常或者抛出一个不同的异常,本测试方法就将失败。
本实例是结合这spring 做的:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
import com.web.myx.cn.UserPo;
/**
*
* junit4 异常测试
* @author Chris
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JunitExceptionTest {
@Autowired
@Qualifier("userPo")
private UserPo userPo;
@Before
public void init(){
userPo.setUser_name("chris");
}
/**
* 通过expected 参数值指定异常类型
*/
@Test(expected=NullPointerException.class)
public void testUserPo(){
assertNotNull(userPo.getUser_name());
}
}