| Maven by Example - 4.9. Writing Unit Tests |
|
|
|
Maven has built-in support for unit tests, and testing is a part of
the default Maven lifecycle. Let’s add some unit tests to our simple
weather project. First, let’s create the
$ cd src/test/java $ cd org/sonatype/mavenbook $ mkdir -p weather/yahoo $ cd weather/yahoo At this point, we will create two unit tests. The first will test the
Simple Weather’s YahooParserTest Unit Test. package org.sonatype.mavenbook.weather.yahoo;
import java.io.InputStream;
import junit.framework.TestCase;
import org.sonatype.mavenbook.weather.Weather;
import org.sonatype.mavenbook.weather.YahooParser;
public class YahooParserTest extends TestCase {
public YahooParserTest(String name) {
super(name);
}
public void testParser() throws Exception {
InputStream nyData = getClass().getClassLoader()
.getResourceAsStream("ny-weather.xml");
Weather weather = new YahooParser().parse( nyData );
assertEquals( "New York", weather.getCity() );
assertEquals( "NY", weather.getRegion() );
assertEquals( "US", weather.getCountry() );
assertEquals( "39", weather.getTemp() );
assertEquals( "Fair", weather.getCondition() );
assertEquals( "39", weather.getChill() );
assertEquals( "67", weather.getHumidity() );
}
}
This In the same directory, create a file named
Simple Weather’s WeatherFormatterTest Unit Test. package org.sonatype.mavenbook.weather.yahoo;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.sonatype.mavenbook.weather.Weather;
import org.sonatype.mavenbook.weather.WeatherFormatter;
import org.sonatype.mavenbook.weather.YahooParser;
import junit.framework.TestCase;
public class WeatherFormatterTest extends TestCase {
public WeatherFormatterTest(String name) {
super(name);
}
public void testFormat() throws Exception {
InputStream nyData = getClass().getClassLoader()
.getResourceAsStream("ny-weather.xml");
Weather weather = new YahooParser().parse( nyData );
String formattedResult = new WeatherFormatter().format( weather );
InputStream expected = getClass().getClassLoader()
.getResourceAsStream("format-expected.dat");
assertEquals( IOUtils.toString( expected ).trim(),
formattedResult.trim() );
}
}
The second unit test in this simple project tests the
|
