Skip to content

Instantly share code, notes, and snippets.

View Rene-Frerichs's full-sized avatar

Rene-Frerichs

View GitHub Profile
@Test
public void assertJ() throws Exception {
assertThatThrownBy(this::methodThrowsIllegalArgument)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid Argument");
}
@Rene-Frerichs
Rene-Frerichs / ExpectedExceptionRule.java
Last active November 26, 2015 15:45
JUnit exception test with expected exception rule.
@Rule
public ExpectedException thrownException = ExpectedException.none();
@Test
public void exceptionRule() {
thrownException.expect(IllegalArgumentException.class);
thrownException.expectMessage("Invalid Argument");
methodThrowsIllegalArgument();
}
@Rene-Frerichs
Rene-Frerichs / ExpectedException.java
Created November 26, 2015 15:28
JUnit Exception Testing with ExpectedException
@Test(expected = IllegalArgumentException.class)
public void expected() {
methodThrowsIllegalArgument();
}
@Rene-Frerichs
Rene-Frerichs / ClassicExceptionTest.java
Created November 26, 2015 15:25
Classic JUnit exception testing
@Test
public void tryCatch() {
try {
methodThrowsIllegalArgument();
fail("Expected IllegalArgumentException!");
} catch (IllegalArgumentException exception) {
assertThat(exception.getMessage(), is("Invalid Argument"));
}
}
@Rene-Frerichs
Rene-Frerichs / ExceptionTestingTest.java
Last active November 26, 2015 15:44
Different alternatives for exception testing with JUnit
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ExceptionTestingTest {
@Rene-Frerichs
Rene-Frerichs / AssertFile.java
Last active October 26, 2015 19:31
AssertJ File Assertion
@Test
public void fileAssertion() {
File file = createFile("openKnowledge.txt", "offen, kundig, gut!");
assertThat(file).exists().hasExtension("txt").isFile().isRelative();
assertThat(contentOf(file)).startsWith("offen").contains("kundig").endsWith("gut!");
}
@Rene-Frerichs
Rene-Frerichs / SoftAssertion.java
Last active November 6, 2015 09:44
AssertJ SoftAssertion
@Rule
public JUnitSoftAssertions softly = new JUnitSoftAssertions();
String openKnowledge = "offen, kundig, gut!";
@Test
public void exampleNormalAssertion() {
assertThat(openKnowledge).startsWith("kundig").endsWith("offen");
// -> java.lang.AssertionError: Expecting: <"offen, kundig, gut!"> to start with: <"kundig">
}