开发者

How to do unit testing without the use of a library?

I've never written a single unit test. But since every article I read, they are talking about unit testing. I figured I should get started with开发者_Python百科 it.

But how?

Can someone point me to a very simple unit tested hello world example? Without the use of jUnit or the likes.


If you don't want to use any other libraries then you have to do a lot of work yourself. For example, suppose you have a class with one function that you want to test:

class Foo {
    public int bar(int input);
}

You can now write a test class:

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();
    }
}

This is a very basic example but it shows you how you could write your own unit tests.

That said, I strongly recommend using a library like JUnit. It gives you a lot for free and removes a huge amount of boiler-plate code that you would have to write yourself. It also generates nice reports and (when combined with something like Cobertura) can give you a fairly comprehensive view of how complete your testing is.


Check out the JUnit Cook's Tour.

I'd recommend either JUnit (version 4.4 or higher) or TestNG.


I would recomend that you DO use some other library. It sounds like what you're wanting to do is build your own Unit testing library. The problem with that is that any basic problems with your code, any logical errors you may be making, you're just as likely to make in your Unit testing code as well, so that yes, your Units pass testing, but only because they do what you expect them to do, not because it's what they actually SHOULD be doing using strict standards in whatever language your using.

Let's say you wrote a function that compares a true/false and returns 0. in PHP (0==false)=true but (0===false)=false if you've coded for scenario 1 but ignored scenario 2 and then write a unit test that tests that scenario 1 is valid but ignores scenario 2 (which you might if you always code that way) then your unit test passes based on what you have defined but is still wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜