I'm really new to java.
I'm running some JUnit tests on a constructor. The constructor is such that if it is given a null or an empty string for one of its parameters, it's supposed to throw an exception.
When I test this constructor in JUnit with a null or an empty string parameter, I get a red bar, even though I'm almost 100% sure that the constructor method does indeed throw an exception when such parameters are passed in to it.
Shouldn't there be a green bar in JUnit if the method throws an exception the way it is supposed to? Or is it that when you are supposed to get a red bar when the exception throwing works the way it is supposed to?
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.
are you sure you told it to expect the exception?
for newer junit (>= 4.7), you can use something like (from here)
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testRodneCisloRok(){
exception.expect(IllegalArgumentException.class);
exception.expectMessage("error1");
new RodneCislo("891415",dopocitej("891415"));
}
and for older junit, this:
@Test(expected = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}
If your constructor is similar to this one:
public Example(String example) {
if (example == null) {
throw new NullPointerException();
}
//do fun things with valid example here
}
Then, when you run this JUnit test you will get a green bar:
@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
Example example = new Example(null);
}
An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.
And using Matchers, you can test the part of message you are interested:
exception.expectMessage(containsString("income: -1000.0"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With