---
title: "使用Junit4的时候一个小问题"
author: "slowman"
date: "2010-01-30T16:25:48Z"
tags: []
categories: ["编程语言"]
slug: "junit4"
draft: false
lastmod: "2010-07-23T20:41:08Z"
id: 583969
url: "https://slowman.iteye.com/blog/583969"
---

JUnit4.X出来已经很久了，一直没有去尝试使用一下，（这也是自己的一个不足，不太喜欢去尝试新新鲜的工具。我想这对于IT人员来，恐怕是一个很大的不足。）今天突然心血来潮去体验了一下。却发现一个奇怪的问题。如下描述：

我在自己的电脑上写了一个测试程序，用来体验Junit4.7的新功能，没有任何问题，但是呢，将自己的代码拷另外一机子上，然后打开就不行了。Eclipse老是提示assertThat(\*\*\*)这个方法unresolved，我的第一反就是是没有导入hamcrest包，但是检查buildpath发现导入了hamcrest的core和library这两个包，也就是说是对的呀，但是MyEclipse就是说有问题。百思不得其解，今天在网上看到另外一篇blog，才明白了原因所在。

      原来我在新工程里面，添加junit4的jar包的时候，是添加了MyEclipse7.5自带的junit library.而在自己在之前做测试的时候，使用的是自己从网上下载的junit  jar包，然后手动导入的。junit4中有一个新的特性就是使用assertThat（）这个测试方法。这个方法需要引入hamcrest包，**而使用hamcrest时不能用IDE提供的Junit4 JAR包，因为classloader不同。**所以把工程中的junit4 library remove掉，然后手工导入下载的junit包，问题得到解决。

顺便介绍一下Junit4常用东东吧。

    Junit4.x中的annotations：

   @Test（expected=java.lang.ArimeticException,timeout=300），

   @Ignore：被忽略的测试方法，

   @Before：在所有测试方法之前运行，

   @After：在所有测试方法之后运行，

   @BeforeClass（static方法）：在测试对象生成之前运行，可以用于开启数据库等一些操作，

   @AfterClass(static方法)：在所有测试方法结束之后运行。

 

 

Error与Failure：后者呢表示测试失败，而前者表示程序运行错误，此时是不管测试失败与否的。

 

测试类如下：

 

 

 

 

```
package cn.edu.ccnu.inc.lwm.junit; 
public class A {
 /** * @param args */ 
public int add(int x,int y) 
{ return x+y ; } 
public int sub(int x,int y ) 
{ return x-y ; } } 
```

 

 

 

 

 

 

 

 

 

 

 

 

 

针对A的测试类：

```
package cn.edu.ccnu.inc.lwm.junit.test; 
import static org.junit.Assert.*; 
import org.hamcrest.Matcher; 
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 cn.edu.ccnu.inc.lwm.junit.A;
import static org.hamcrest.Matchers.* ;
/**
 * 注意:要使用assertThat()必须引入 org.hamcrest.Matchers.* ;
 * 
 * @date 2010-1-20 *
 * @author Administrator
 * 
 */ 
public class ATest { private A obj = null; 
/**
 * *
 * 
 * @BeforeClass
 * @AfterClass 必须是静态的. * 在实例还没有生成的时候就加载了。 *
 *             用在当我们要在测试之前获取一些资源的时候，比如说取得数据库连接，可以用@BeforeClass() *
 *             测试完毕后，释放资源的时候使用@afterClass() *
 */ 
}
@BeforeClass
public static void beforeClass() 
{ System.out.println("before class"); } 
@AfterClass 
public static void afterClass() 
{ System.out.println("after class"); } 
/**
 * *
 * 
 * @Before
 * @After 是指所有的测试方法执行之前或者之后 *
 * @throws Exception
 */
@Before
public void setUp() throws Exception 
{	 obj = new A();
	System.out.println("before"); 
} 
@After 
public void tearDown() throws Exception 
{ 
	System.out.println("after"); 
} 
/** * 表明这是一个测试方法 * */
@Test 
public void testAdd()
{ 
	int z = obj.add(3, 5) ; 
    assertEquals("应该是相等的",8, z) ;
    assertThat(z, is(8)) ; }
}
/**
 * *
 * 
 * @Ignore 标明这个测试方法要忽略掉. *
 */
@Ignore @Test public void testSub()
{ int z = obj.sub(9,2) ; 
   assertThat(z, is(7)) ; }
} 
}
```