Search code examples
unit-testingtesting

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 it.

But how?

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


Solution

  • 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.