Java and Technology weblog
mvn -Dtest=com.your.package.YourTest test
Run from within the folder that contains the src (as in src/test/java) folder, which will likely be either be the root of your maven project, or in one of your modules.
This is covered maven surefire plugin docs but the example always confuses me slightly since it omits the packages names, which are required.
However, I quickly after discovered FEST Assertions, and happily switched to it. It provides the same improved test readability and failure messages as Hamcrest, but has the extra benefit of enabling IDE auto completion, rather than having to search through package and class docs to find the right matcher.
Unfortunately, Fest seems to not longer be actively developed. The last stable release of the 1.x branch, 1.4, was released way back in 2011, and the new 2.x branch never made it to a stable release and hasn’t had a commit since June 2013.
Unit tests are used to verify that a piece of code operates as the developer expects it to. Sometimes, that means checking that the code throws expected exceptions too. JUnit is the standard for unit testing in Java and provides several mechanisms for verifying exceptions were thrown. This article explores the options and their relative merits.
Software quality is critical to consistently and continually delivering new features to our users. This articles covers the importance of software quality and how to deliver it via unit testing, Test Driven Development and clean code in general.
- Click: Run -> Edit Configuration
- Select your test configuration (or add a new one)
- In VM parameters, add
(Or wherever your log4j properties file is)
That’s it. The test should now run with log4j logging (although obviously you need to have the necessary log4j jars available).
This example uses a windows file format, but will work equally well with *nix.
As a follow up to the Hamcrest post I made yesterday, I wanted to post an example of my own Hamcrest matcher implementation. This matcher tests if a string contains a specified number of substrings.
An example usage could be:
String sql = "select a,b,c from tableA"; assertThat(sql, hasNumberOfSubstrings(",", 2));
I have also attached a jar which includes the associated unit tests, although you will need the hamcrest-unit-test project to compile, which can be downloaded as part of the hamcrest all-in-one jar.
Hamcrest is a framework for writing matcher objects. Matchers have a variety of uses, but are particularly useful when writing unit tests. Instead of using JUnit’s assertEquals methods, we use Hamcrest’s assertThat construct with one (or more) of the many Matchers available. For example
A small change in this example, but Hamcrest’s benefits are many, enabling you to write much more flexible tests that are easier to read and have more meaningful failure messages.