2012-07-13 15 views
1

我的测试世界的新手,我开始与junit.I测试我的应用程序有一个类测试我的applcation使用JUnit

public class Sender implements Runnable 
{ 
    private httpd server; 

    public Sender(httpd server_) 
    { 
    this.server = server_ 
    } 

    public void run() 
    { 

    ...  

    } 
} 

如果从httpd类接收的参考我会测试是null。我读了我必须使用assertNotNull,但我不清楚创建SenderTest类后做了什么。 我读了SenderTest里面创建的类(通过junit框架创建)一个方法有注释@Test。但之后我该怎么办?

+0

可以的,如果你想要断言你还可以添加你的“测试”代码 – radimpe 2012-07-13 07:44:06

+1

一个参数你的方法不是null,这听起来像输入验证,而不是单元测试。这应该是班级发件人的一个断言。对于单元测试,您可以调用发件人类并查看它是否有效。 – Thilo 2012-07-13 07:44:45

回答

3

这不是你应该测试你的班级的方式。

httpd是否为空不是Sender合同的一部分,而是Sender的客户。

我建议你做到以下几点:

  • 定义如果它收到null作为server_参数如何Sender应该表现。

    我会推荐例如说类似于如果server_null,则引发IllegalArgumentException

  • 创建一个测试,声明它的行为如指定。例如,通过做这样

    try { 
        new Sender(null); 
        fail("Should not accept null argument"); 
    } catch (IllegalArgumentException expected) { 
    } 
    
+3

+1。单元测试检查'Sender'是否工作。如果其他代码正确使用'Sender',则不会。这将是输入验证,也许使用'assert'关键字。 – Thilo 2012-07-13 07:45:50

+0

所以如果我的课有其他课的参考,我不能测试它的行为,对吧? – Mazzy 2012-07-13 07:50:26

+0

当然可以。你想测试什么样的行为? – aioobe 2012-07-13 07:54:11

2

的东西,如果你需要使用JUnit测试代码,可以考虑这种方式。

这是JUnit测试应该如何工作的例子:


public class Factorial { 

    /** 
    * Calculates the factorial of the specified number in linear time and constant space complexity.<br> 
    * Due to integer limitations, possible calculation of factorials are for n in interval [0,12].<br> 
    * 
    * @param n the specified number 
    * @return n! 
    */ 
    public static int calc(int n) { 
     if (n < 0 || n > 12) { 
      throw new IllegalArgumentException("Factorials are defined only on non-negative integers."); 
     } 

     int result = 1; 

     if (n < 2) { 
      return result; 
     } 

     for (int i = 2; i <= n; i++) { 
      result *= i; 
     } 

     return result; 
    } 

} 

import static org.junit.Assert.*; 

import org.junit.Test; 

public class FactorialTest { 

    @Test 
    public void factorialOfZeroShouldBeOne() { 
     assertEquals(1, Factorial.calc(0)); 
    } 

    @Test 
    public void factorialOfOneShouldBeOne() { 
     assertEquals(1, Factorial.calc(1)); 
    } 

    @Test 
    public void factorialOfNShouldBeNTimesFactorialOfNMinusOne() { 
     for (int i = 2; i <= 12; i++) { 
      assertEquals(i * Factorial.calc(i - 1), Factorial.calc(i)); 
      System.out.println(i + "! = " + Factorial.calc(i)); 
     } 
    } 

    @Test(expected = IllegalArgumentException.class) 
    public void factorialOfNegativeNumberShouldThrowException() { 
     Factorial.calc(-1); 
     Factorial.calc(Integer.MIN_VALUE); 
    } 

    @Test(expected = IllegalArgumentException.class) 
    public void factorialOfNumberGreaterThanTwelveShouldThrowException() { 
     Factorial.calc(13); 
     Factorial.calc(20); 
     Factorial.calc(50); 
    } 
}