JUnit4学习小结

最近看了下JUnit4的文档,把一些用法总结下。
1.测试类不用实现任何接口和继承任何类。对于要测试的方法,在方法头上加上JUint4的Anotation @Test即可

Java代码
  1. package  junit.study;  
  2. import   static  junit.framework.Assert.*;  
  3. public   class  JunitStudyTest1{  
  4.   
  5. @Test   
  6. public   void  testMethod1(){  
  7. //......   
  8.   
  9. }  
  10. }  
package junit.study;
import static junit.framework.Assert.*;
public class JunitStudyTest1{

@Test
public void testMethod1(){
//......

}
}



2.测试方法名不需要严格的格式要求,如上例子,方法可以随便取名。包括setUp()和tearDown()。只需要在这些方法上加上Anotation @Before,@After即可

Java代码
  1.      @Before   
  2.     public   void  initMethod()  throws  Exception  
  3.     {  
  4. ...  
  5.     }  
  6.   
  7.     @After   
  8.     public   void  finalMehtod()  throws  Exception  
  9.     {  
  10. ...  
  11.     }  
    @Before
    public void initMethod() throws Exception
    {
...
    }

    @After
    public void finalMehtod() throws Exception
    {
...
    }


3.注意@BeforeClass,@AfterClass与@Before,@After的区别

@BeforeClass和@AfterClass
在每个类中只有一个方法能被注解。
方法名是不相关的
每个类运行一次
在当前类的@BeforeClass方法运行前先运行超类的@BeforeClass方法。在超类中声明的@AfterClass方法将在所有当前类的该方法运行后才运行。
必须是公共和非静态的。
即使一个@BeforeClass方法抛出一个异常,所有的@AfterClass方法也保证被运行。

@Before和@After
多个方法能被注解,但其执行的顺序未特别指定,且不运行重载方法。
方法名是不相关的
在每个测试方法运行前或运行后运行
超类中的@Before在所有子类的该方法运行前运行。在超类中的@After在在所有子类的该方法运行后才运行。
必须是公共和非静态的。
即使一个@Before或者@Test方法抛出一个异常,所有的@After方法也保证被运行。


  如果你仅有一次需要分配和释放昂贵的资源,那么@BeforeClass和@AfterClass可能很有用。在我们的例子 中,AbstractParent使用这些在startTestSystem()和stopTestSystem()方法上的注解启动和停止整个测试系 统。

4.Suite使用

Java代码
  1. @RunWith (Suite. class )  
  2. @Suite .SuiteClasses({  
  3.     OneTest.class ,  
  4.     TwoTest.class ,  
  5.     ThreeTest.class   
  6. })  
  7. public   class  TestSuite  
  8. {  
  9.    
  10. }  
@RunWith(Suite.class)
@Suite.SuiteClasses({
    OneTest.class,
    TwoTest.class,
    ThreeTest.class
})
public class TestSuite
{
 
}


5.暂时屏蔽一个测试方法@Ignore

   
Java代码
  1. @Ignore ( "not ready yet" )  
  2. @Test   
  3. public   void  testMethod3()  
  4. {  
  5.       
  6. }  
    @Ignore("not ready yet")
    @Test
    public void testMethod3()
    {
        
    }


6.Junit4 Assert API
http://junit.sourceforge.net/javadoc_40/org/junit/Assert.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值