JUnit - Test d'exceptions attendues
Dans JUnit, il existe 3 façons de tester les exceptions attendues:
-
@Test, attribut "attendu" facultatif -
Try-catch et toujours
fail() -
@RuleExpectedException
P.S Tested with JUnit 4.12
1. Attribut attendu @Test
Utilisez ceci si vous souhaitez uniquement tester le type d'exception, reportez-vous ci-dessous:
Exception1Test.java
package com.example;
import org.junit.Test;
import java.util.ArrayList;
public class Exception1Test {
@Test(expected = ArithmeticException.class)
public void testDivisionWithException() {
int i = 1 / 0;
}
@Test(expected = IndexOutOfBoundsException.class)
public void testEmptyList() {
new ArrayList<>().get(0);
}
}
2. Essayer-attraper et toujours échouer ()
C'est un peu old school, largement utilisé dans JUnit 3. Testez le type d'exception ainsi que le détail de l'exception. Référez-vous ci-dessous:
Exception2Test.java
package com.example;
import org.junit.Test;
import java.util.ArrayList;
import static junit.framework.TestCase.fail;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class Exception2Test {
@Test
public void testDivisionWithException() {
try {
int i = 1 / 0;
fail(); //remember this line, else 'may' false positive
} catch (ArithmeticException e) {
assertThat(e.getMessage(), is("/ by zero"));
//assert others
}
}
@Test
public void testEmptyList() {
try {
new ArrayList<>().get(0);
fail();
} catch (IndexOutOfBoundsException e) {
assertThat(e.getMessage(), is("Index: 0, Size: 0"));
}
}
}
Always remember the fail()!
Si la ligne que vous voulez tester n’a pas lancé d’exception et que vous avez oublié de mettre lesfail(), le test sera réussi (faux positif).
3. @Rule ExpectedException
Cette règleExpectedException (depuis JUnit 4.7) vous permet de tester à la fois le type d'exception et également le détail de l'exception, identique à la méthode «2. Try-catch
and always fail()», mais d'une manière plus élégante:
Exception3Test.java
package com.example;
import com.example.examples.CustomerService;
import com.example.examples.exception.NameNotFoundException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.hasProperty;
public class Exception3Test {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testDivisionWithException() {
thrown.expect(ArithmeticException.class);
thrown.expectMessage(containsString("/ by zero"));
int i = 1 / 0;
}
@Test
public void testNameNotFoundException() throws NameNotFoundException {
//test type
thrown.expect(NameNotFoundException.class);
//test message
thrown.expectMessage(is("Name is empty!"));
//test detail
thrown.expect(hasProperty("errCode")); //make sure getters n setters are defined.
thrown.expect(hasProperty("errCode", is(666)));
CustomerService cust = new CustomerService();
cust.findByName("");
}
}
NameNotFoundException.java
package com.example.examples.exception;
public class NameNotFoundException extends Exception {
private int errCode;
public NameNotFoundException(int errCode, String message) {
super(message);
this.errCode = errCode;
}
public int getErrCode() {
return errCode;
}
public void setErrCode(int errCode) {
this.errCode = errCode;
}
}
CustomerService.java
package com.example.examples;
import com.example.examples.exception.NameNotFoundException;
public class CustomerService {
public Customer findByName(String name) throws NameNotFoundException {
if ("".equals(name)) {
throw new NameNotFoundException(666, "Name is empty!");
}
return new Customer(name);
}
}