JUnit 4.12
I'm currently writing a test for a class methods. Here is how it looks like
public interface MyInterface{ //method declaration } public class MyClass implements MyInterface{ private int a; private in b; public MyClass(int a, int b){ if(a <= b + 5) throw new IllegalArgumentException("Invalid arguments"); this.a = a; this.b = b; } //methods } Now I want to test this class:
public class MyClassTest{ private static final int THRESHOLD = 1000; private MyClass mc; @Before public void init(){ Random rnd = new Random(); int a = rnd.nexInt(THRESHOLD), b = rnd.nexInt(THRESHOLD); mc = new MyClass(a, b); } } But in this case, init() might throw an exception. So I'd like to test preserving invariants as well as initialize an object in order to test its other methods.
How to do this correctly in JUnit?
aandb. One tests if the case wherealower thanb+5, one tests whereais equal tob+5and the last one tests whereais larger thanb+5. UsingRandomis not necessary or helpful here.@before? If you want to test the exception, just just a Test.@Before. Normally, one uses@Beforewithin a Test-class to initialize some values needed for the tests. This method does not call any tests, the JUni-Runner does that for you.