﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-皇家方舟-随笔分类-junit</title><link>http://www.blogjava.net/xixuui/category/15556.html</link><description /><language>zh-cn</language><lastBuildDate>Tue, 27 Feb 2007 14:25:04 GMT</lastBuildDate><pubDate>Tue, 27 Feb 2007 14:25:04 GMT</pubDate><ttl>60</ttl><item><title>如何测试自定义断言</title><link>http://www.blogjava.net/xixuui/archive/2006/11/24/83329.html</link><dc:creator>阿辉</dc:creator><author>阿辉</author><pubDate>Fri, 24 Nov 2006 09:48:00 GMT</pubDate><guid>http://www.blogjava.net/xixuui/archive/2006/11/24/83329.html</guid><wfw:comment>http://www.blogjava.net/xixuui/comments/83329.html</wfw:comment><comments>http://www.blogjava.net/xixuui/archive/2006/11/24/83329.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/xixuui/comments/commentRss/83329.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/xixuui/services/trackbacks/83329.html</trackback:ping><description><![CDATA[由于Junit中没有对数组比较的断言，因此自定义了以下断言：<br />/**<br />  * asserts two String arrays are equal。<br />  */<br /> public static void assertEquals(final String[] expected,<br />         final String[] actual)<br /> {<br />  if(expected == null &amp;&amp; actual == null)<br />  {<br />   assertTrue(true);<br />  }<br />  else if(expected.length != actual.length)<br />  {<br />   fail("expected length is :" + expected.length + "but was:"<br />     + actual.length);<br />  }<br />  else<br />  {<br />   for(int i = 0; i &lt; expected.length; i++)<br />   {<br />    assertEquals("第" + (i + 1) + "个元素不相等", expected[i], actual[i]);<br />   }<br />  }<br /> }<br /><br />可是又怎么对该方法进行测试呢？<img src ="http://www.blogjava.net/xixuui/aggbug/83329.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixuui/" target="_blank">阿辉</a> 2006-11-24 17:48 <a href="http://www.blogjava.net/xixuui/archive/2006/11/24/83329.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Junit4功能 先睹为快. (译文) （转）</title><link>http://www.blogjava.net/xixuui/archive/2006/09/22/71246.html</link><dc:creator>阿辉</dc:creator><author>阿辉</author><pubDate>Fri, 22 Sep 2006 01:44:00 GMT</pubDate><guid>http://www.blogjava.net/xixuui/archive/2006/09/22/71246.html</guid><wfw:comment>http://www.blogjava.net/xixuui/comments/71246.html</wfw:comment><comments>http://www.blogjava.net/xixuui/archive/2006/09/22/71246.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/xixuui/comments/commentRss/71246.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/xixuui/services/trackbacks/71246.html</trackback:ping><description><![CDATA[
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="100%">
										<h1>An early look at JUnit 4</h1>
										<p id="subtitle">
												<em>Upcoming release promises evolution in testing</em>
										</p>
								</td>
						</tr>
				</tbody>
		</table>
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr valign="top">
								<td width="100%">
										<p>难度级别: 中</p>
										<p>
												<a href="/margiex#author">
														<strong>
																<font color="#006bad">Elliotte Harold </font>
														</strong>
												</a>(<a href="mailto:elharo@metalab.unc.edu?subject=An early look at JUnit 4&amp;cc=dwxed@us.ibm.com"><strong><font color="#006bad">elharo@metalab.unc.edu</font></strong></a>), Adjunct Professor, Polytechnic University<br /></p>
										<p>2005-9-15 （译）</p>
										<p>原文：<a href="http://www-128.ibm.com/developerworks/java/library/j-junit4.html"><strong><font color="#006bad">http://www-128.ibm.com/developerworks/java/library/j-junit4.html</font></strong></a></p>
										<blockquote>JUnit 是JAVA语言事实上的标准测试库。JUnit 4是三年以来最具里程碑意义的一次发布。它的新特性主要是针对JAVA5中的标记（annotation）来简化测试，而不是利用子类、反射或命名机制。本文将讲述如何使用JUnit 4，当前前提是你最好具有JUnit的使用经验．</blockquote>
										<p>JUnit, 由Kent Beck 和 Erich Gamma开发，几乎是JAVA开发最重要的第三方工具。正如Martin Fowler 所说，“在软件开发领域，从来就没有如此少的代码起到了如此重要的作用“。由于JUnit，JAVA代码变得更健壮，更可靠，BUG也比以前更少。由于JUnit (由Smalltalk's的SUnit得来) 的出现，随后产生了许多xUnit的测试工具，如nUnit (.NET), pyUnit (Python), CppUnit (C++), dUnit (Delphi) 和其它不同平台及语言的测试相关的工具。</p>
										<p>虽然JUnit也只是一个工具，但其产生的思想和技术却较其架构更意义重大。单元测试，测试先行的编程方式，测试驱动的开发方式，并非必须由JUNIT实现，也不一定要用SWing实现GUI界面。JUNIT最近的一次更新是在三年前，但它比其它大多数有BUG的框架都要健壮，更重要的是，JAVA一直在改进。现在JAVA支持泛型，枚举，可变长度参数，以及标记语言（开创了开发可重用框架的新局面）。</p>
										<p>JUnit's的停滞不前使得那些想要变革的开发人员换其它测试工具．挑战者有Bill Venners的Artima SuiteRunner和Cedric Beust的TestNG．这些工具库虽然有值得推荐的功能，但没有任何一款的地位能与JUNIT相比，没有任何一款工具被其它业界产品如Ant, Maven, Eclipse广泛支持．因此Beck 和Gamma双开始利用JAVA5的新特性来开发新版的JUNIT，目的是利用JAVA5中的标记特性使得单元测试开发更容易。Beck说：“JUNIT4的主要目的是通过简化JUNIT的使用鼓励更多的开发人员写更多的测试”。虽然会与以前的版本兼容，但JUNIT4与从JUNIT1.0就开始的版本相比会有一个非常大的变化． </p>
										<p>
												<strong>注意: </strong>修改基本框架是一把双刃剑，虽然JUNIT4的目的是清晰的，但细节仍有许多不同，因此本文只是一个简单的介绍，并不是最终文档． </p>
										<p>
												<a name="N1007F">
														<span class="atitle">
																<strong>测试方法</strong>
														</span>
												</a>
										</p>
										<p>以前所有版本的JUNIT都使用命名机制和反射来定位测试，下面的代码测试1+1= 2：</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">import junit.framework.TestCase;

public class AdditionTest extends TestCase {

  private int x = 1;
  private int y = 1;
  
  public void testAddition() {
    int z = x + y;
    assertEquals(2, z);
  }

}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>而在JUNIT 4中，测试方法由<strong>@Test</strong> 标记说明，如下：</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">import org.junit.Test;
import junit.framework.TestCase;

public class AdditionTest extends TestCase {

  private int x = 1;
  private int y = 1;
  
  @Test public void testAddition() {
    int z = x + y;
    assertEquals(2, z);
  }

}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>使用标记的好处是你不用将所有测试方法命名为 <code>testFoo()</code>, <code>testBar()等等以"test"开头的方法，下面的方法也同样可以工作：</code></p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">import org.junit.Test;
import junit.framework.TestCase;

public class AdditionTest extends TestCase {

  private int x = 1;
  private int y = 1;
  
  @Test public void additionTest() {
    int z = x + y;
    assertEquals(2, z);
  }

}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>下面的代码也同样正确：</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">import org.junit.Test;
import junit.framework.TestCase;

public class AdditionTest extends TestCase {

  private int x = 1;
  private int y = 1;
  
  @Test public void addition() {
    int z = x + y;
    assertEquals(2, z);
  }

}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>这种命名机制最大的优点是更适合你的待测试类或方法名称，例如，你可以使用ListTEst.contains()测试 <code>List.contains()</code>;使用ListTest.addAll()测试 <code>List.add()等等．</code></p>
										<p>
												<code>
														<strong>TestCase</strong>还可以继续使用，但你没有必须再扩展为子类，只要你声明了@Test，你可以将测试方法放在任何类中，当然如要访问assert等方法，你必须要引用junit.Assert类，如下：</code>
										</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">import org.junit.Assert;

public class AdditionTest {

  private int x = 1;
  private int y = 1;
  
  @Test public void addition() {
    int z = x + y;
    Assert.assertEquals(2, z);
  }

}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>你也可以使用JDK5中的新特性(static import)使得跟以前版本一样简单： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">import static org.junit.Assert.assertEquals;

public class AdditionTest {

  private int x = 1;
  private int y = 1;
  
  @Test public void addition() {
    int z = x + y;
    assertEquals(2, z);
  }

}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>这种方法测试受保护的方法非常容易，因为你可以在测试类中继承有受保护方法的类． </p>
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<a name="N100DD">
														<span class="atitle">SetUp 和TearDown</span>
												</a>
										</p>
										<p>JUnit 3 中<strong>test runners</strong> 会在每个测试之前自动调用 <code>setUp()方法。此方法主要用于初始化变量，打开日志，重置环境变量等。下面是XOM's <code>XSLTransformTest中的</code></code><code>setUp()方法：</code></p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">protected void setUp() {
        
    System.setErr(new PrintStream(new ByteArrayOutputStream()));
        
    inputDir = new File("data");
    inputDir = new File(inputDir, "xslt");
    inputDir = new File(inputDir, "input");
        
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>在JUnit 4中，你仍然可以在每个测试前初始化变量和配置环境,，然而，这些操作可以不用在Setup()中完成，你可以在初始化方法前面添加<strong>@Beforer</strong> 来表示，如下： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">@Before protected void initialize() {
        
    System.setErr(new PrintStream(new ByteArrayOutputStream()));
        
    inputDir = new File("data");
    inputDir = new File(inputDir, "xslt");
    inputDir = new File(inputDir, "input");
        
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>你也可以有多个方法标记有＠Before，所有方法都会在每个测试之前执行： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">@Before protected void findTestDataDirectory() {
    inputDir = new File("data");
    inputDir = new File(inputDir, "xslt");
    inputDir = new File(inputDir, "input");
}
    
 @Before protected void redirectStderr() {
    System.setErr(new PrintStream(new ByteArrayOutputStream()));
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>清除环境与JUNIT3 差不多，在JUNIT3中使用 <code>tearDown()方法，下面的代码是结束测试时回收内存：</code></p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">protected void tearDown() {
  doc = null;
  System.gc();   
} </code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>在JUnit 4中，你还可以使用<strong>@After</strong>标记来说明： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">@After protected void disposeDocument() {
  doc = null;
  System.gc();   
} </code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>与 <code>@Before一样，你也可以有多个标记有</code><code>@After的清除方法，每个都会在执行完每个测试后执行。</code></p>
										<p>最后，你不需要在父类中明确调用这些初始化或清除方法．test runner会自动调用这些标记的方法．子类中的@Before方法在父类的@Before方法之后执行（这与构造函数的执行顺序一样），而@After方法刚好相反，子类中的@After方法先执行．然而，多个@Before和@After方法的执行顺序就是未知的．</p>
										<p>
												<font face="宋体">
														<strong>测试集范围的初始化</strong>
												</font>
										</p>
										<p>JUnit 4中引入了一项JUNIT3没有的新特性，类级别的setUp()和tearDown()，即在一个类的所有测试前执行初始化，并在所有测试完成后执行清除。 </p>
										<p>例如，一个测试类中的每个测试都要用到一个数据库连接或网络连接，或其它很耗资源初始化或释放的资源，用不着在每个测试方法前后进行操作，而只需要在测试类开始前后执行即可。下面的示例是使用第三方的库进行错误，在执行所有测试前将错误先重定向到非标准输出，然后在所有测试结束后再输出到需要的地方，这样就不会影响到测试过程中产生的其它信息。</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">// This class tests a lot of error conditions, which
// Xalan annoyingly logs to System.err. This hides System.err 
// before each test and restores it after each test.
private PrintStream systemErr;
    
@BeforeClass protected void redirectStderr() {
    systemErr = System.err; // Hold on to the original value
    System.setErr(new PrintStream(new ByteArrayOutputStream()));
}
    
@AfterClass protected void tearDown() {
    // restore the original value
    System.setErr(systemErr);
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>上面的操作没有必须在每个测试前后执行。然而要注意的是，这种方法可能影响测试间的结果，如果一个测试改变了初始化的对象，而这个对象可能是其它测试的输入，那么测试的结果可能不正确，这种方法将依赖测试的顺序并可能引入BUG。当优化测试性能，并且当你改进了配置和基准测试后而仍然很慢时，如数据库连接或网络问题，你才需要考虑使用这种方法。只有这样，你才能每天执行多次测试。 </p>
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<a name="N10173">
														<span class="atitle">
																<strong>异常测试</strong>
														</span>
												</a>
										</p>
										<p>异常测试是JUNIT4中的最大的改进，以前异常测试是通过try catch实现，当抛出异常时，在try的最后添加一条fail()语句实现．如下： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">public void testDivisionByZero() {
    
    try {
        int n = 2 / 0;
        fail("Divided by zero!");
    }
    catch (ArithmeticException success) {
        assertNotNull(success.getMessage());
    }
    
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>这种方法不仅难看，而且造成无论成功或失败，代码覆盖工具都不能执行某些代码．而在JUnit 4中，你可以在要抛出异常的代码中添加标记来声明一个异常是期望的： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">@Test(expected=ArithmeticException.class) public void divideByZero() {
    int n = 2 / 0;
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>如果没有异常抛出，上面的测试则会失败，如果你想知道异常的详细信息或其它情况，你还是要使用try catch才行 <br /></p>
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<font face="宋体">
														<strong>需要忽略的测试</strong>
												</font>
										</p>
										<p>也许你有些测试需要很长时间才能执行完成，并非是这个测试应该跑得快，而是它做的很复杂和很慢的工作造成的．如访问远程网络错误，需要很久才能有反馈．如果你不想让这种测试破坏你整个测试过程，你可能想跳过这个测试．当然也有可能某个测试超出控制范围而失败．如W3C XInclude测试集中自动识别一些JAVA不支持的Unicode代码．为了防止这些测试总是通不过，可以使用标记 <code><strong>@Ignore</strong>跳过这些测，如下：</code></p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">// Java doesn't yet support the UTF-32BE and UTF32LE encodings
    @Ignore public void testUTF32BE() 
      throws ParsingException, IOException, XIncludeException {
      
        File input = new File(
          "data/xinclude/input/UTF32BE.xml"
        );
        Document doc = builder.build(input);
        Document result = XIncluder.resolve(doc);
        Document expectedResult = builder.build(
          new File(outputDir, "UTF32BE.xml")
        );
        assertEquals(expectedResult, result);
                
    }</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>test runner不会执行这些测试，但会说明这些测试被跳过了。在命令行测试界面中，字母“I”会表示测试跳过，或“E”表示测试失败，而不是用点”."表示成功．</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">$ java -classpath .:junit.jar org.junit.runner.JUnitCore nu.xom.tests.XIncludeTest
JUnit version 4.0rc1
.....I..
Time: 1.149

OK (7 tests)</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>要注意的是，假设这些测试由于某种理由放在最开始，如果你以后一直忽略这些测试，那些需要被测试的代码可能有问题而不会被检测到。因此忽略测试只是一个临时解决方法，并不是一个解决任何问题的真正办法。 </p>
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<font face="宋体">
														<strong>时间测试</strong>
												</font>
										</p>
										<p>性能测试是单元测试中最头疼的问题，JUnit 4也未完全解决此问题， 你可以在JUNIT4的测试方法中添加一个时间参数。如果测试时间超过参数，则测试失败。如下，如果测试时间超过0.5秒，则此测试失败：</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">
@Test(timeout=500) public void retrieveAllElementsInDocument() {
    doc.query("//*");
} </code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>除基准性能测试外，时间测试在网络测试方面也很有用．如果一个远端的主机或数据当掉或太慢，你可以跳过此测试而不用阻塞在这里，好的测试集可以在作了一些改动后很快的一遍一遍的执行，可能一天数十次．设置一个超时让测试更快的执行，下面的示例中如果分析http://www.ibiblio.org/xml 的时间超过２秒，则测试失败．</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">
@Test(timeout=2000) 
  public void remoteBaseRelativeResolutionWithDirectory()
   throws IOException, ParsingException {
      builder.build("http://www.ibiblio.org/xml");
  } </code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<a name="N101CD">
														<span class="atitle">
																<strong>新的断言</strong>
														</span>
												</a>
										</p>
										<p>JUnit 4 增加了两上断文方法用于比较数组：</p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">
public static void assertEquals(Object[] expected, Object[] actual)
public static void assertEquals(String message, Object[] expected, 
Object[] actual)
</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>这两个方法采用最直接方法比较，如果数组长度相同，且每个对应的元素相同，则比较成功，否则不成功．参数为空的情况也作了考虑． <br /></p>
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<font face="宋体">
														<strong>需要补充的地方</strong>
												</font>
										</p>
										<p>JUnit 4是一个非常基本的框架，还不是以前版本的升级。JUNIT3的开发人员会发现有些功能没有。 </p>
										<ul>
												<li>
														<font face="宋体">最大的特点就是没有GUI测试界面，当测试正确时是绿色条，而出错时红色的，你也可以在Eclipse中集成JUNIT使用，但JUNIT4既没有AWT也没有SWING的GUI测试界面；</font>
												</li>
												<li>
														<font face="宋体">另一个让人吃惊的是失败（期望错误）和错误（未预计的异常错误）没有明显区别，在JUNIT3中开发人员可以区分这两种情况，而在JUNIT4中不行；</font>
												</li>
												<li>
														<font face="宋体">最后一个特点是JUNIT中没有用于建立一堆测试类的<code>suite()方法，取而代之的是，采用变长参数传递未知数量的测试给test runner。</code></font>
												</li>
										</ul>
										<p>没有GUI测试界面的确不方便，但其它改变简化了JUNIT的使用，从当前JUNIT的操作手册和FAQ的数量就知道，而JUNIT4的文档将不会需要这么多。 </p>
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<a name="N101FA">
														<span class="atitle">
																<strong>编译和运行JUnit 4</strong>
														</span>
												</a>
										</p>
										<p>现在JUnit 4还没有发布编译版本，如果想体验版本的乐趣，则需要从CVS中获取源代码。分支标签是"Version4" (see <a href="/margiex#resources"><strong><font color="#006bad">Resources</font></strong></a> ).要注意的是大部分文档是根据JUNIT3编写的，还未同步更新。需要Java 5才能编译JUnit 4，因为大量使用了标记，泛型其其它JDK5中的新特性。 </p>
										<p>执行测试的命令行方式与JUNIT3有点区别，你现在要使用 <code>org.junit.runner.JUnitCore</code> 类进行测试，如下： </p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">
$ java -classpath .:junit.jar org.junit.runner.JUnitCore 
  TestA TestB TestC...
JUnit version 4.0rc1

Time: 0.003

OK (0 tests)</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>
												<a name="N10212">
														<span class="smalltitle">
																<strong>兼容性</strong>
														</span>
												</a>
										</p>
										<p>Beck 和Gamma在努力保持后向和前向兼容性。JUnit 4可以直接运行根据JUNIT3编写的测试类，而不用任何修改，直接将各测试类的全名传递给test runner即可．test runner会根据不同的测试类调用不同的测试框架版本． </p>
										<p>后向兼容性有点麻烦，即在JUNIT3中执行根据JUNIT4写的测试类，之所以要这样是因为在一个集成环境如Ecplise中，不需要升级到JUNIT4也可以测试JUNIT4的测试类，从而避免工具IDE的升级。为了让JUNIT4的测试类在JUNI3中能执行，你需要一个适配类<code><strong>JUnit4TestAdapter</strong>封装JUNIT3的测试类，如下代码：</code></p>
										<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
												<tbody>
														<tr>
																<td>
																		<pre>
																				<code class="section">public static junit.framework.Test suite() {
  return new JUnit4TestAdapter(AssertionTest.class);    
}</code>
																		</pre>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<p>而JAVA方面，JUNIT4一点兼容性都没有，因为完全依赖于JDK5的新特性，因此不可能在JAVA1.4上面执行JUNIT4。</p>
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<strong>还有...</strong>
										</p>
										<p>JUnit 4远未结束，还有许多需要补充，如文档，现在不推荐将以前的测试类升级到JUNIT4。当然JUNIT4的开发速度很快，其计划也很快会实现，JAVA1.4的开发人员仍然可以使用JUNIT3.8，而使用JAVA5的人员可以考虑是否采用JUNIT4了，因为在特性上更适合。 </p>
										<br />
										<table class="no-print" cellspacing="0" cellpadding="0" align="right">
												<tbody>
														<tr align="right">
																<td>
																		<table cellspacing="0" cellpadding="0" border="0">
																				<tbody>
																						<tr>
																								<td valign="center">
																										<br />
																								</td>
																								<td valign="top" align="right">
																										<a class="fbox" href="/margiex#main">
																												<b>
																														<font color="#006bad">Back to top</font>
																												</b>
																										</a>
																								</td>
																						</tr>
																				</tbody>
																		</table>
																</td>
														</tr>
												</tbody>
										</table>
										<br />
										<br />
										<p>
												<a name="resources">
														<span class="atitle">
																<strong>资源</strong>
														</span>
												</a>
										</p>
										<ul>
												<li>
														<a href="http://www.pragmaticprogrammer.com/starter_kit/utj/index.html">
																<i>
																		<strong>
																				<font color="#006bad">Pragmatic Unit Testing in Java with JUnit</font>
																		</strong>
																</i>
														</a> (Andy Hunt and Dave Thomas, Pragmatic Programmers, 2003): An excellent introduction to unit testing.<br /><br /></li>
												<li>
														<a href="http://www.amazon.com/exec/obidos/ISBN=1932394230/ref=nosim/cafeaulaitA/">
																<i>
																		<strong>
																				<font color="#006bad">JUnit Recipes: Practical Methods for Programmer Testing</font>
																		</strong>
																</i>
														</a> (J. B. Rainsberger, Manning, 2004): One of the most widely cited and referenced books on JUnit.<br /><br /></li>
												<li>
														<a href="http://www.beust.com/testng/">
																<strong>
																		<font color="#006bad">TestNG</font>
																</strong>
														</a>: Cedric Beust's framework pioneered the annotation based testing style now used in JUnit 4.<br /><br /></li>
												<li>"<a href="http://www.ibm.com/developerworks/java/library/j-testng/"><strong><font color="#006bad">TestNG makes Java unit testing a breeze</font></strong></a>" (Filippo Diotalevi, developerWorks, January 2005): An introduction to TestNG.<br /><br /></li>
												<li>"<a href="http://www.ibm.com/developerworks/library/j-ant/"><strong><font color="#006bad">Incremental development with Ant and JUnit</font></strong></a>" (Malcolm Davis, developerWorks, November 2000): Explores the benefits of unit testing, in particular using Ant and JUnit, with code samples.<br /><br /></li>
												<li>"<a href="http://www.ibm.com/developerworks/java/library/j-xp042203/index.html"><strong><font color="#006bad">Demystifying Extreme Programming: Test-driven programming</font></strong></a>" (Roy Miller, developerWorks, April 2003): Find out how test-driven programming can revolutionize your productivity and quality as a programmer, and learn the mechanics of writing tests.<br /><br /></li>
												<li>"<a href="http://www.ibm.com/developerworks/edu/i-dw-wes-junit-i.html"><strong><font color="#006bad">Keeping critters out of your code</font></strong></a>" (David Carew, et. al., developerWorks, June 2003): Learn how you can use JUnit in conjunction with WebSphere Application Developer. <br /><br /></li>
												<li>"<a href="http://www.ibm.com/developerworks/java/library/j-cobertura/"><strong><font color="#006bad">Measure test coverage with Cobertura</font></strong></a>" (Elliotte Rusty Harold, developerWorks, May 2005): Learn to identify untested code and locate bugs with this handy open source tool. <br /><br /></li>
										</ul>
										<br />
										<b>下载测试版本</b>
										<br />
										<ul>
												<li>
														<a href="http://cvs.sourceforge.net/viewcvs.py/junit/junit/?only_with_tag=Version4">
																<strong>
																		<font color="#006bad">JUnit 4</font>
																</strong>
														</a>: Download the newest version of JUnit the SourceForge CVS repository; be sure to use the branch tag "Version4."<br /><br /></li>
										</ul>
								</td>
						</tr>
				</tbody>
		</table>原文：<a href="/margiex">http://www.blogjava.net/margiex</a><img src ="http://www.blogjava.net/xixuui/aggbug/71246.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixuui/" target="_blank">阿辉</a> 2006-09-22 09:44 <a href="http://www.blogjava.net/xixuui/archive/2006/09/22/71246.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>从文件中取测试数据进行单元测试</title><link>http://www.blogjava.net/xixuui/archive/2006/09/20/70800.html</link><dc:creator>阿辉</dc:creator><author>阿辉</author><pubDate>Wed, 20 Sep 2006 06:40:00 GMT</pubDate><guid>http://www.blogjava.net/xixuui/archive/2006/09/20/70800.html</guid><wfw:comment>http://www.blogjava.net/xixuui/comments/70800.html</wfw:comment><comments>http://www.blogjava.net/xixuui/archive/2006/09/20/70800.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/xixuui/comments/commentRss/70800.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/xixuui/services/trackbacks/70800.html</trackback:ping><description><![CDATA[ public void testPopSortFromFile() throws IOException<br /> {<br />  @SuppressWarnings("unused")<br />  String line = "";<br />  FileReader myFileReader = new FileReader<font color="#ff0000">("com/liyingcheng/testFiles/TestPopSort.txt");//相对路径<br /></font>  BufferedReader myBufferedReader=new BufferedReader(myFileReader);<br />  while((line = myBufferedReader.readLine())!=null)<br />  {<br />   if(line.startsWith("#"))<br />   {<br />    continue;<br />   }<br />   <br />   String[] tokens = line.split(",");<br />   <br />   int[] actual = {Integer.parseInt(tokens[0]),Integer.parseInt(tokens[1]),Integer.parseInt(tokens[2])};<br />   int[] expected = {Integer.parseInt(tokens[3]),Integer.parseInt(tokens[4]),Integer.parseInt(tokens[5])};<br />   testSinglePopSort(expected,actual);<br />  }<br /> }<br /><img src ="http://www.blogjava.net/xixuui/aggbug/70800.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixuui/" target="_blank">阿辉</a> 2006-09-20 14:40 <a href="http://www.blogjava.net/xixuui/archive/2006/09/20/70800.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>junit assert() 使用实例</title><link>http://www.blogjava.net/xixuui/archive/2006/09/19/70537.html</link><dc:creator>阿辉</dc:creator><author>阿辉</author><pubDate>Tue, 19 Sep 2006 07:13:00 GMT</pubDate><guid>http://www.blogjava.net/xixuui/archive/2006/09/19/70537.html</guid><wfw:comment>http://www.blogjava.net/xixuui/comments/70537.html</wfw:comment><comments>http://www.blogjava.net/xixuui/archive/2006/09/19/70537.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/xixuui/comments/commentRss/70537.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/xixuui/services/trackbacks/70537.html</trackback:ping><description><![CDATA[
		<p>package com.liyingcheng.netTest;</p>
		<p>
				<br />import com.liyingcheng.net.Sort;</p>
		<p>import junit.framework.Test;<br />import junit.framework.TestCase;<br />import junit.framework.TestSuite;<br />import junit.xiaoxuhui.Sum;</p>
		<p>
				<br />public class SortTest extends TestCase<br />{<br /> // Sort popObj = new Sort();</p>
		<p> public SortTest(String name)<br /> {<br />  super(name);<br /> }</p>
		<p>
				<br /> protected void setUp() throws Exception<br /> {<br />  super.setUp();<br /> }</p>
		<p>
				<br /> protected void tearDown() throws Exception<br /> {<br />  super.tearDown();<br /> }</p>
		<p>
				<br /> static public void assertEquals(int[] expected, int[] actual)<br /> {<br />  for(int i = 0; i &lt; expected.length; i++)<br />  {<br />   assertEquals(null, expected[i], actual[i]);<br />  }<br /> }</p>
		<p>
				<br /> public void testPopSort()<br /> {<br />  int[] expected = new int[] {1, 2, 3, 4};<br />  assertEquals(expected, Sort.popSort(new int[] {1, 2, 4, 3}));<br />  assertEquals(expected, Sort.popSort(new int[] {1, 2, 3, 4}));<br />  assertEquals(expected, Sort.popSort(new int[] {1, 3, 4, 2}));<br />  assertEquals(expected, Sort.popSort(new int[] {1, 3, 2, 4}));<br />  assertEquals(expected, Sort.popSort(new int[] {2, 1, 4, 3}));<br />  assertEquals(expected, Sort.popSort(new int[] {2, 4, 1, 3}));<br />  assertEquals(expected, Sort.popSort(new int[] {3, 2, 4, 1}));<br />  assertEquals(new int[] {1, 2}, Sort.popSort(new int[] {2, 1}));<br />  // assertEquals(new int[]{1,3,2,4},popObj.popSort(new int[]{1,2,4,3}));<br />  // assertEquals(new int[]{1,2,3,4},popObj.popSort(new int[]{1,2,4,3}));<br /> }</p>
		<p>
				<br /> public void testCreateArray()<br /> {<br />  assertEquals(4, Sort.createArray(4).length);<br /> }</p>
		<p>
				<br /> public void testGetSum()<br /> {<br />  assertEquals(5050, Sum.getSum(1, 100));<br /> }</p>
		<p>
				<br /> public void testFalse()<br /> {<br />  assertFalse(false);<br />  assertTrue(true);<br /> }</p>
		<p>
				<br /> public void testIsNull()<br /> {<br />  String str1 = "";<br />  int[] arr1 = {};<br />  String str2 = null;<br />  int[] arr2 = null;<br />  assertNotNull(str1);<br />  assertNotNull(arr1);<br />  assertNull(str2);<br />  assertNull(arr2);<br />  // assertNull(str);<br /> }</p>
		<p>
				<br /> public void testNull()<br /> {<br /> }</p>
		<p>
				<br /> public void testNotSame()<br /> {<br />  String str1 = "123";<br />  String str2 = "123";<br />  String str3 = new String(str1);<br />  String str4 = new String("123");<br />  int one = 1;<br />  int first = 1;<br />  assertSame(one, first);<br />  assertSame(str1, str2);<br />  assertNotSame(str3, str4);<br />  //fail("hahahahahahahah");<br />  /*<br />   * assertNotSame(one,first); assertNotSame(str1,str2);<br />   */<br /> }</p>
		<p>
				<br /> public static Test suite()<br /> {<br />  TestSuite suite = new TestSuite("Test sort!");<br />  suite.addTestSuite(SortTest.class);<br />  return suite;<br /> }</p>
		<p>}<br /></p>
<img src ="http://www.blogjava.net/xixuui/aggbug/70537.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixuui/" target="_blank">阿辉</a> 2006-09-19 15:13 <a href="http://www.blogjava.net/xixuui/archive/2006/09/19/70537.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>junit数组比较</title><link>http://www.blogjava.net/xixuui/archive/2006/09/18/70350.html</link><dc:creator>阿辉</dc:creator><author>阿辉</author><pubDate>Mon, 18 Sep 2006 09:30:00 GMT</pubDate><guid>http://www.blogjava.net/xixuui/archive/2006/09/18/70350.html</guid><wfw:comment>http://www.blogjava.net/xixuui/comments/70350.html</wfw:comment><comments>http://www.blogjava.net/xixuui/archive/2006/09/18/70350.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/xixuui/comments/commentRss/70350.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/xixuui/services/trackbacks/70350.html</trackback:ping><description><![CDATA[以下断言只是对整型数组进行比较，如需其它数据类型的比较则只需修改相应的数据类型；<br />/**<br />  * Asserts that two int arrays are equal. If they are not an<br />  * AssertionFailedError is thrown.<br />  */<br /> static public void assertEquals(int[] expected, int[] actual )<br /> {<br />  for(int i = 0; i &lt; expected.length; i++)<br />  {<br />   assertEquals(null, expected[i], actual[i]);<br />  }<br /> }<br /><img src ="http://www.blogjava.net/xixuui/aggbug/70350.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixuui/" target="_blank">阿辉</a> 2006-09-18 17:30 <a href="http://www.blogjava.net/xixuui/archive/2006/09/18/70350.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>TestSuite的使用</title><link>http://www.blogjava.net/xixuui/archive/2006/09/18/70275.html</link><dc:creator>阿辉</dc:creator><author>阿辉</author><pubDate>Mon, 18 Sep 2006 05:59:00 GMT</pubDate><guid>http://www.blogjava.net/xixuui/archive/2006/09/18/70275.html</guid><wfw:comment>http://www.blogjava.net/xixuui/comments/70275.html</wfw:comment><comments>http://www.blogjava.net/xixuui/archive/2006/09/18/70275.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/xixuui/comments/commentRss/70275.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/xixuui/services/trackbacks/70275.html</trackback:ping><description><![CDATA[您定义自己的TestCase，并使用TestRunner来运行测试，事实上TestRunner并不直接运行 TestCase上的单元方法，而是透过TestSuite，TestSuite可以将数个TestCase在一起，而让每个TestCase保持简单。<br /><br />来看看一个例子：<br /><ul><li>MathToolTest.java </li></ul><pre>package onlyfun.caterpillar.test;<br /><br />import onlyfun.caterpillar.MathTool;<br />import junit.framework.TestCase;<br /><br />public class MathToolTest extends TestCase {<br />    public MathToolTest(String testMethod) {<br />        super(testMethod);<br />    }<br /><br />    public void testGcd() {<br />        assertEquals(5, MathTool.gcd(10, 5));<br />    }<br /><br />    public static void main(String[] args) {<br />        junit.textui.TestRunner.run(MathToolTest.class);<br />    }<br />}</pre><br />在这个例子中，您并没有看到任何的TestSuite，事实上，如果您没有提供任何的TestSuite，TestRunner会自己建立一个，然後这个 TestSuite会使用反射（reflection）自动找出testXXX()方法。<br /><br />如果您要自行生成TestSuite，则在继承TestCase之後，提供静态的（static）的suite()方法，例如：<br /><div style="MARGIN-LEFT: 40px"><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">public static Test suite() {</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">     return new TestSuite(MathTool.class);</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">}</span><br /></div><br />如果您没有提供任何的TestSuite，则TestRunner就会像上面这样自动为您建立一个，并找出testXXX()方法，您也可以如下面定义 suite()方法：<br /><div style="MARGIN-LEFT: 40px"><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">public static Test suite() {</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">     TestSuite suite = new TestSuite(MathTool.class);</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">     suite.addTest(new MathToolTest("testGcd"));</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">     return suite;</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">}</span><br /></div> <br />JUnit并没有规定您一定要使用testXXX()这样的方式来命名您的测试方法，如果您要提供自己的方法（当然JUnit 鼓励您使用testXXX()这样的方法名称），则可以如上撰写，为了要能够使用建构函式提供测试方法名称，您的TestCase必须提供如下的建构函 式：<br /><div style="MARGIN-LEFT: 40px"><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">public MathToolTest(String testMethod) {</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">    super(testMethod);</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">}</span><br /></div> <br /><br />如果要加入更多的测试方法，使用addTest()就可以了，suite()方法传回一个TestSuite物件，它与 TestCase都实作了Test介面，TestRunner会调用TestSuite上的run()方法，然後TestSuite会将之委托给 TestCase上的run()方法，并执行每一个testXXX()方法。<br /><br />除了组合TestCase之外，您还可以将数个TestSuite组合在一起，例如：<br /><div style="MARGIN-LEFT: 40px"><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">public static Test suite() { </span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">    TestSuite suite= new TestSuite(); </span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">    suite.addTestSuite(TestCase1.class);</span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">    suite.addTestSuite(TestCase2.class); </span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">    return suite; </span><br style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace" /><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">}</span><br /></div> <br />如此之来，您可以一次运行所有的测试，而不必个别的运行每一个测试案例，您可以写一个运行全部测试的主测试，而在使用TestRunner时呼叫 suite()方法，例如：<br /><div style="MARGIN-LEFT: 40px"><span class="postbody"></span><span style="FONT-WEIGHT: bold; FONT-FAMILY: Courier New,Courier,monospace">junit.textui.TestRunner.run(TestAll.suite());</span><br /></div><br />TestCase与TestSuite都实作了Test介面，其运行方式为 Command 模式 的一个实例，而TestSuite可以组合数个TestSuite或TestCase，这是 Composite 模式 的一个实例。<img src ="http://www.blogjava.net/xixuui/aggbug/70275.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/xixuui/" target="_blank">阿辉</a> 2006-09-18 13:59 <a href="http://www.blogjava.net/xixuui/archive/2006/09/18/70275.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>