Testing two JSON objects for equality ignoring child order in Java [closed]

Try Skyscreamer’s JSONAssert. Its non-strict mode has two major advantages that make it less brittle: Object extensibility (e.g. With an expected value of {id:1}, this would still pass: {id:1,moredata:’x’}.) Loose array ordering (e.g. [‘dog’,’cat’]==[‘cat’,’dog’]) In strict mode it behaves more like json-lib’s test class. A test looks something like this: @Test public void testGetFriends() { … Read more

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once. In general, you use @BeforeClass when multiple tests need to share the same computationally expensive setup … Read more

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit. Per the JUnit docs: import static org.junit.jupiter.api.Assertions.assertThrows; @Test void exceptionTesting() { MyException thrown = assertThrows( MyException.class, () -> myObject.doThing(), “Expected doThing() to … Read more

Java: How to test methods that call System.exit()?

Indeed, Derkeiler.com suggests: Why System.exit() ? Instead of terminating with System.exit(whateverValue), why not throw an unchecked exception? In normal use it will drift all the way out to the JVM’s last-ditch catcher and shut your script down (unless you decide to catch it somewhere along the way, which might be useful someday). In the JUnit … Read more

When do Java generics require

First – I have to direct you to http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html — she does an amazing job. The basic idea is that you use <T extends SomeClass> when the actual parameter can be SomeClass or any subtype of it. In your example, Map<String, Class<? extends Serializable>> expected = null; Map<String, Class<java.util.Date>> result = null; assertThat(result, is(expected)); You’re … Read more

Maven does not find JUnit tests to run

By default Maven uses the following naming conventions when looking for tests to run: Test* *Test *Tests (has been added in Maven Surefire Plugin 2.20) *TestCase If your test class doesn’t follow these conventions you should rename it or configure Maven Surefire Plugin to use another pattern for test classes.

How to mock a final class with mockito

Mockito 2 now supports final classes and methods! But for now that’s an “incubating” feature. It requires some steps to activate it which are described in What’s New in Mockito 2: Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to … Read more