1

我是测试世界的新手,我开始用 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在那之后我必须做什么?

4

2 回答 2

3

这不是你应该测试你的课程的方式。

是否httpd为 null 不是合同的一部分,Sender而是Sender.

我建议您执行以下操作:

  • 定义如果它作为参数Sender接收应该如何表现。nullserver_

    例如,我会建议说类似If server_is null, an IllegalArgumentExceptionis throws。.

  • 创建一个断言其行为符合指定的测试。例如通过做类似的事情

    try {
        new Sender(null);
        fail("Should not accept null argument");
    } catch (IllegalArgumentException expected) {
    }
    
于 2012-07-13T07:44:22.840 回答
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);
    }
}
于 2012-07-13T07:48:58.567 回答