Tải bản đầy đủ - 585 (trang)
apendix B: Brief JUnit 3.8 tutorial

apendix B: Brief JUnit 3.8 tutorial

Tải bản đầy đủ - 585trang

APPENDIX B:



471



Brief JUnit 3.8 tutorial

import java.io.*;

public class TestConsoleLogger extends

junit.framework.TestCase {



BC



private static final String EOL =

System.getProperty("line.separator");

private ConsoleLogger logger;

private PrintStream originalSysOut, originalSysErr;

private ByteArrayOutputStream sysOut, sysErr;



D



EF



@Override protected void setUp() {

logger = new ConsoleLogger();

originalSysOut = System.out;

originalSysErr = System.err;

sysOut = new ByteArrayOutputStream();

sysErr = new ByteArrayOutputStream();

System.setOut(new PrintStream(sysOut));

System.setErr(new PrintStream(sysErr));

}

@Override protected void tearDown() {

System.setOut(originalSysOut);

System.setErr(originalSysErr);

}



FG



public void testInfoLevelGoesToSysOut() throws Exception {

logger.info("msg");

streamShouldContain("[INFO] msg" + EOL, sysOut);

}



H

I



public void testErrorLevelGoesToSysErr() throws Exception {

logger.error("Houston...");

streamShouldContain("[ERROR] Houston..." + EOL, sysErr);

}



J



private void streamShouldContain(String expected,

ByteArrayOutputStream stream) {

assertEquals("Stream content doesn’t match expected. ",

expected, stream.toString());

}



1)



}



B



The name of the class should indicate that it’s a test—for example, have the class

name start with Test.



C

D



We extend from JUnit’s TestCase class.

The instance variables set up in the setUp() method represent the common fixture for the test methods.



472



APPENDIX B:



Brief JUnit 3.8 tutorial



E

F



We can prepare a known state for the test by overriding the protected setUp()

method.

If using Java 5, it’s good to add the @Override annotation to setUp() and tearDown() to avoid typos.



G

H



We can clean up after our test by overriding the protected tearDown() method.



I

J



Test methods can declare any exceptions—JUnit catches them.



1)



Extending TestCase gives us, among other things, a bunch of assertion methods

such as assertEquals().



All public void methods starting with test are considered test cases by the JUnit 3.8

TestRunner.

We can declare any number of helper methods as long as they don’t look like test

methods.



appendix C:

Brief EasyMock tutorial



473



474



APPENDIX C:



Brief EasyMock tutorial

import static org.easymock.EasyMock.*;

import org.easymock.EasyMock;

import org.junit.Test;



B



public class TestInternetRelayChat {

@Test

public void messagesAreOnlyDeliveredToOtherClients()

throws Exception {

String msg = "Maisk Maisk!";

Client koskela = EasyMock.createMock(Client.class);

Client freeman = EasyMock.createMock(Client.class);

Client himberg = EasyMock.createMock(Client.class);

expect(himberg.onMessage("lasse",

msg)).andReturn(true);



D



freeman.onMessage("lasse", msg);

expectLastCall().andReturn(true);



E



replay(freeman, koskela, himberg);



F



InternetRelayChat irc = new InternetRelayChat();

irc.join("inhuman", freeman);

irc.join("vilbert", himberg);

Prompt prompt = irc.join("lasse", koskela);

prompt.say(msg);

verify(freeman, koskela, himberg);



C



G



H



}

}



B

C

D

E

F

G

H



Import static utility methods from EasyMock and the class itself.

Ask EasyMock to create mock objects for the given interface.

Record expected interactions.

This is an alternative, functionally equivalent syntax for the previous syntax.

When we’re done recording expectations, we move the mocks to replay mode.

With everything set up, we exercise the code under test.

We ask the mock objects to verify that the expected interactions took place.



appendix D:

Running tests with Ant



475



476



APPENDIX D



Running tests with Ant



Apache Ant is the de facto build tool used by Java developers all around the world.

Not surprisingly, Ant has had JUnit integration as long as I can remember. Here’s

a quick tutorial for creating an Ant script that runs our unit tests and cranks out a

pretty HTML report of the results. If you’re not familiar with Ant, please refer to

the online documentation1 or grab one of the excellent books on the topic.2

Let’s start our little tutorial and see what kind of a project we’re dealing with.



Apache Ant and JUnit 4 compatibility

JUnit 4 support was introduced in the 1.7 release of Apache Ant, which means

that you’ll need to downgrade your tests to use JUnit 3.8 if you don’t have or cannot upgrade your Ant version to the 1.7 branch. The versions of Ant and JUnit

you’re using do not, however, affect your build script.



D.1



Project directory structure

From the perspective of build scripts, we’re not interested in what our Java classes

can do. We only care about the code compiling, us being able to run all automated tests as part of our build, and getting a nice report out of the test run,

which we can browse for details on test failures and so forth. The project’s directory structure dictates a lot of what our build script needs to do. Consider the relatively simple directory structure depicted in listing D.1.

Listing D.1



Sample directory structure



/SampleProject

/src

/main

Production code

/com/tddinaction/.../ProductionCode.java

under src/main

/test

Test code under

/com/tddinaction/.../TestCode.java

src/test

/bin

/classes-main

Compiled code follows

/com/tddinaction/...

similar separation

/classes-test

/com/tddinaction/...



B



C



D



1



2



Especially the User’s Manual (http://ant.apache.org/manual) and the Ant Wiki (http://

wiki.apache.org/ant).

I would personally recommend Ant in Action by Steve Loughran and Erik Hatcher (Manning Publications, 2007). It’s basically a 2nd edition of their earlier book, Java Development with Ant (Manning Publications, 2002).



APPENDIX D



Running tests with Ant



477



/lib

Dependencies

/main

separated for

commons-logging.jar

production and

/test

test code

junit.jar

build.xml

Build script in root of project directory



E



F



Our source code is split into two directories: B src/main and C src/test. Having

separate source trees provides for an easier distinction between test code and production code and also because makes writing build scripts a lot easier—everything

under X is about X, everything under Y is about Y.

We also have a similar split for compiled class files. D Compiled production

code goes to bin/classes-main, and compiled test code goes to bin/classes-test.

Not surprisingly, E the libraries we depend on are separated under lib/main and

lib/test. Once again, the separation makes it easier to manage the different sets of

dependencies for runtime and development and simplifies the act of creating a

deployment archive, which should only contain compiled production code and

only runtime dependencies.

The Ant build script, F build.xml, is located in the root of the project directory. And speaking of the build script, we’re ready to look inside it. Let’s start with

the first step of getting all code compiled.



D.2



The basics: compiling all source code

For this project, the build.xml used for compiling all source code to their respective output directories might look something like listing D.2.

Listing D.2 build.xml for compiling all code for the SampleProject





















B



Target for cleaning up

compilation artifacts











Different compilation

class paths for

production and

test code



478



APPENDIX D



Running tests with Ant







C



Target for compiling

all source code








debug="on" classpathref="classpath.main" />




debug="on" classpathref="classpath.test" />





Different

compilation

class paths for

production

and test code







This is familiar to those who have seen Ant build scripts. The script in listing D.2

provides the developer with two targets to execute: B clean and C compile. With

Ant installed, typing ant clean on the command prompt deletes all compiled

class files. Typing ant compile compiles all .java source files into the bin directory.

Typing ant clean compile first deletes existing class files and then compiles everything from scratch. And, because the project’s default target is configured as compile, just typing ant is the same as typing ant compile.

But what about running those tests we’re now compiling?



D.3



Adding a target for running tests

JUnit is integrated into Ant through the task. In order to make running

our unit tests part of our build, we need to add a new target to build.xml, which

uses the task. Listing D.3 shows an example of what this new target

might look like.

Listing D.3 build.xml with a test target using Ant’s standard task





Use test target as

default from now on





...



Use property for

output path to

reduce duplication



B











Need everything



in class path



including compiled



test code



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

apendix B: Brief JUnit 3.8 tutorial

Tải bản đầy đủ ngay(585 tr)

×