assert vs. JUnit Assertions

In JUnit4 the exception (actually Error) thrown by a JUnit assert is the same as the error thrown by the java assert keyword (AssertionError), so it is exactly the same as assertTrue and other than the stack trace you couldn’t tell the difference. That being said, asserts have to run with a special flag in … Read more

AssertEquals 2 Lists ignore order

As you mention that you use Hamcrest, So I would pick one of the collection Matchers import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.assertThat; public class CompareListTest { @Test public void compareList() { List<String> expected = Arrays.asList(“String A”, “String B”); List<String> actual = Arrays.asList(“String B”, “String A”); assertThat(“List equality without order”, actual, containsInAnyOrder(expected.toArray())); } }

Reuse spring application context across junit test classes

Yes, this is perfectly possible. All you have to do is to use the same locations attribute in your test classes: @ContextConfiguration(locations = “classpath:test-context.xml”) Spring caches application contexts by locations attribute so if the same locations appears for the second time, Spring uses the same context rather than creating a new one. I wrote an … Read more

Assert regex matches in JUnit

If you use assertThat() with a Hamcrest matcher that tests for regex matches, then if the assertion fails you’ll get a nice message that indicates expected pattern and actual text. The assertion will read more fluently also, e.g. assertThat(“FooBarBaz”, matchesPattern(“^Foo”)); with Hamcrest 2 you can find a matchesPattern method at MatchesPattern.matchesPattern.

How to test an Android Library Project

Quoting the documentation: “There are two recommended ways of setting up testing on code and resources in a library project: You can set up a test project that instruments an application project that depends on the library project. You can then add tests to the project for library-specific features. You can set up a standard … Read more

How can I find out if code is running inside a JUnit test or not?

It might be a good idea if you want to programmatically decide which “profile” to run. Think of Spring Profiles for configuration. Inside an integration tests you might want to test against a different database. Here is the tested code that works public static boolean isJUnitTest() { for (StackTraceElement element : Thread.currentThread().getStackTrace()) { if (element.getClassName().startsWith(“org.junit.”)) … Read more