停止更新,敏捷测试及TestOps解决体系,关注订阅号TestOps

Get Acquainted with the New Advanced Features of JUnit 4

上一篇 / 下一篇  2007-11-21 11:27:03 / 个人分类:JAVA

Learn how to migrate from JUnit 3.8 to JUnit 4. Discover version 4's new features, including extensive use of annotations, and find out the status on IDE integration. 

|WE(P a0
JUnit 4 is a completely different API from the versions that came before it and depends on new features of Java 5.0 (annotations, static import…). As you'll see, JUnit 4 issimpler, richer, and easier to use and introduces more flexible initialization and cleanup, timeouts, and parameterized test cases.

wI2w R@)H0Nothing beats a bit of code for clarification. I'll use an example that I can use to illustrate different test cases throughout the article: a calculator. The sample calculator is very simple, inefficient, and even has a few bugs; it only manipulates integers and stores the result in a static variable. Substract method does not return a valid result, multiply is not implemented yet, and it looks like there is a bug on the squareRoot method: It loops infinitely. These bugs will help illustrate the efficiency of the tests in JUnit 4. You can switch this calculator on and off and you can clear the result. Here is the code:

package calc;

public class Calculator {

    private static int result;          // Static variable where the result is stored

    public void add(int n) {
        result = result + n;
    }

    public void substract(int n) {
        result = result - 1;          //Bug : should be result = result - n
    }

    public void multiply(int n) {}     //Not implemented yet

    public void divide(int n) {
        result = result / n;
    }

    public void square(int n) {
        result = n * n;
    }

    public void squareRoot(int n) {
        for (; ;) ;                    //Bug : loops indefinitely
    }

    public void clear() {               // Cleans the result
        result = 0;
    }

    public void switchOn() {          // Swith on the screen, display "hello", beep
        result = 0;                    // and do other things that calculator do nowadays
    }

    public void switchOff() { }	     // Display "bye bye", beep, switch off the screen

    public int getResult() {
        return result;
    }
}
http://www.devx.com/Java/Article/31983/0/page/1

TAG: jnuit JAVA

 

评分:0

我来说两句

Open Toolbar