浏览 919 次
锁定老帖子 主题:Use JUnit
该帖已经被评为隐藏帖
作者 正文
   发表时间:2012-07-05  

Junit  A programmer-oriented testing framework for Java

Simple Test Case[1]How do you write testing code?

The simplest way is as an expression in a debugger. You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness".

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something, here is what you do:

  1. Annotate a method with @org.junit.Test
  2. When you want to check a value, import org.junit.Assert.* statically, call assertTrue() and pass a boolean that is true if the test succeeds
For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:
@Test public void simpleAdd() {     
Money m12CHF= new Money(12, "CHF");      
Money m14CHF= new Money(14, "CHF");      
Money expected= new Money(26, "CHF");      
Money result= m12CHF.add(m14CHF);      
assertTrue(expected.equals(result)); 
}
If you want to write a test similar to one you have already written, write a Fixture instead.


Create a new project de.vogella.junit.first. We want to create the unit tests in a separate folder. The creation of a separate folder for tests is not mandatory. But it is a good practice to keep the code separated from the regular code. You might even create a separate project for the test classes, but we skip this step to make this example simpler.[2]


论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics