如何在不使用库的情况下进行单元测试?

Dem*_*ier 0 testing unit-testing

我从来没有写过一个单元测试。但是因为我读过的每一篇文章,他们都在谈论单元测试。我想我应该开始使用它。

但是如何?

有人可以指出一个非常简单的单元测试 hello world 示例吗?不使用 jUnit 等。

Cam*_*ner 5

如果您不想使用任何其他库,那么您必须自己做很多工作。例如,假设您有一个包含一个要测试的函数的类:

class Foo {
    public int bar(int input);
}
Run Code Online (Sandbox Code Playgroud)

您现在可以编写一个测试类:

class TestFoo {
    public void testBarPositive() {
        Foo foo = new Foo();
        System.out.println(foo.bar(5) == 7);
    }

    public void testBarNegative() {
        Foo foo = new Foo();
        System.out.println(foo.bar(-5) == -7);
    }

    public static void main(String[] args) {
        TestFoo t = new TestFoo();
        t.testBarPositive();
        t.testBarNegative();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常基本的示例,但它向您展示了如何编写自己的单元测试。

也就是说,我强烈建议使用像 JUnit 这样的库。它免费为您提供了很多,并删除了您必须自己编写的大量样板代码。它还可以生成很好的报告,并且(与 Cobertura 之类的东西结合使用时)可以让您相当全面地了解测试的完整程度。