Why use JUnit for testing?

后端 未结 11 1461
忘掉有多难
忘掉有多难 2020-12-12 09:59

Maybe my question is a newbie one, but I can not really understand the circumstances under which I would use junit?

Whether I write simple applications or larger one

11条回答
  •  萌比男神i
    2020-12-12 10:26

    Unit tests ensure that code works as intended. They are also very helpful to ensure that the code still works as intended in case you have to change it later to build new functionalities to fix a bug. Having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.

    Your manual approach by System.out is good but not the best one.This is one time testing that you perform. In real world, requirements keep on changing and most of the time you make a lot of modificaiotns to existing functions and classes. So… not every time you test the already written piece of code.

    there are also some more advanced features are in JUnit like like

    Assert statements

    JUnit provides methods to test for certain conditions, these methods typically start with asserts and allow you to specify the error message, the expected and the actual result

    Some of these methods are

    1. fail([message]) - Lets the test fail. Might be used to check that a certain part of the code is not reached. Or to have failing test before the test code is implemented.
    2. assertTrue(true) / assertTrue(false) - Will always be true / false. Can be used to predefine a test result, if the test is not yet implemented.
    3. assertTrue([message,] condition) - Checks that the boolean condition is true.
    4. assertEquals([message,] expected, actual) - Tests whether two values are equal (according to the equals method if implemented, otherwise using == reference comparison). Note: For arrays, it is the reference that is checked, and not the contents, use assertArrayEquals([message,] expected, actual) for that.
    5. assertEquals([message,] expected, actual, delta) - Tests whether two float or double values are in a certain distance from each other, controlled by the delta value.
    6. assertNull([message,] object) - Checks that the object is null

    and so on. See the full Javadoc for all examples here.

    Suites

    With Test suites, you can in a sense combine multiple test classes into a single unit so you can execute them all at once. A simple example, combining the test classes MyClassTest and MySecondClassTest into one Suite called AllTests:

    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    import org.junit.runners.Suite.SuiteClasses;
    
    @RunWith(Suite.class)
    @SuiteClasses({ MyClassTest.class, MySecondClassTest.class })
    public class AllTests { } 
    

提交回复
热议问题