70 likes | 102 Views
JUnit. What is unit testing?. A unit is the smallest testable part of an application. A unit test automatically verifies the correctness of the unit. There are other kinds of tests: Stress testing Benchmark testing. Why is testing good?.
E N D
What is unit testing? • A unit is the smallest testable part of an application. • A unit test automatically verifies the correctness of the unit. • There are other kinds of tests: • Stress testing • Benchmark testing
Why is testing good? • Due to psychological factors, programmers are bad testers. • A computer can test much faster than a human • “If it ain’t broken, don’t fix it” • A change may introduce new bugs • => We prefer not to change existing code • => Old designs are not updated • => The program cannot adapt to new requirements • With testing you can easily make aggressive changes • Refactoring, XP
Wish list: A testing framework 1. Test expressions: Means for comparing an actual result with an expected result 2. Clear indication of success/failure 3. Clear indication of failed tests 4. Split a long test method into several smaller methods 5. Continue with other tests even if a test fails 6. Continue with other tests even if a test throws an exception 7. No duplication of initialization code of tested objects 8. Side effects should not influence other tests 9. No need to maintain a list of tests
JUnit • JUnit: • http://www.junit.org • http://junit.sourceforge.net • JUnit is a unit testing framework for Java • A test casedefines tools to run a related collection of tests. • A test suiteis a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.
JUnit: Benefits • Writing a test is as simple as writing a method that exercises the code to be tested and defining the expected result. • JUnit gives flexibility in grouping tests and convenient ways to capture and/or summarize test failures. • The Assert class has a bunch of static convenience methods for writing test expressions. • setUp() - initialize the fixture state by overriding • tearDown() - clean-up after a test by overriding • A TestSuite is an object that contains an ordered list of runnable Test objects.
JUnit: Best practices • Use setUp(), tearDown() and not the constructor • Avoid side effects • Keep tests in the mirrored directory structure of source location • Use the TestRunner.run(Class c) method • Testing is meant to improve the quality of the code • => Don’t change a private method into a public one so you can test it • Keeping old test running is just as important as making new ones run • Run tests as often as possible • => The earlier you detect the bug the sooner you solve it • When you work on a bug, write a test case first • => Your work is done when the test case succeeds