ITeye博客

JUnit4学习小结

javeye · 2009-03-23 16:32 · JUnit · Markdown

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

package junit.study;
import static junit.framework.Assert.*;
public class JunitStudyTest1{

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

}
}

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

    @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使用

@RunWith(Suite.class)
@Suite.SuiteClasses({
    OneTest.class,
    TwoTest.class,
    ThreeTest.class
})
public class TestSuite
{
 
}

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


    @Ignore("not ready yet")
    @Test
    public void testMethod3()
    {
        
    }

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

评论(2)

  1. #2 楼 · javeye · 2009-06-04 09:52

    ytsolar writes:

    全哥原来对测试也这么有研究啊

    我很想念你!lc有事干了,没人啊

  2. #1 楼 · ytsolar · 2009-06-03 14:30

    全哥原来对测试也这么有研究啊

评论功能维护中,当前仅展示历史评论。