JUnit/NUnit – Unit testing frameworksjpf/teach/TQS0506/JUnit_NUnit.pdf · JUnit/NUnit – Unit...

Preview:

Citation preview

JUnit/NUnit – Unittesting frameworks

…based on the xUnit architecture

MEI 2003/2004 Nuno Flores

What is JUnit?Open Source Java testing framework used to writeand run repeatable tests.Instance of the xUnit Architecture for unit testingframeworks.Features:

Assertions for testing expected resultsTest fixtures for sharing common test dataTest Suites for easily organizing and running testsGraphical and textual test runners

Originally written by Erich Gamma and Kent Beck

JUnit(xUnit) traceback…xUnit first incarnation: SUnit (SmallTalk)JUnit: “Test infected – Programmers Love WritingTests”Extreme Programming, “Embrace Change”

Kent Beck, Martin Fowler, Ron Jeffries, Erich GammaLightweight development philosophyValues: Simplicity, Courage, Communication, FeedbackBest Practices: Pair-Programming, Small Iterations, Colaborative Ownership, Integrate Often, Refactor Often, KISS, DNO, Test-driven programming

XP Practices Overview

Test-Driven ProgrammingSimplicityMinimalist approachTest-First

During Development - When you need to add new functionality to the system, write the tests first. Then, you will be done developing when the test runs. During Debugging - When someone discovers a defect in your code, first write a test that will succeed if the code is working. Then debug until the test succeeds.

Focus on needed functionality

Test-Driven ProgrammingPractical Guidelines

You are forced to define precisely what a method does.You know where to begin writing a method.You know when you are done writing a method.You know the minimal scaffolding needed to run a method.You know when you are done.

“Once you get them running, make sure they stay running”

xUnit ArchitectureObject-Oriented architecture for development of unit testingframeworks.

Have an object (TestCase) manage the execution of a singletest. Each test should be isolated from the others, so it creates all itsdata before executing and destroys it when it's done (setUp() andtearDown()). Composites of tests (TestSuite) allow many tests to be runtogether. Passing a CollectingParameter (TestResult) to the testsas they run allows the collection of statistics. That's the framework--three objects (TestCase, TestSuite, TestResult).

RudyUnit, SUnit, CppUnit, Unit++, PerlUnit, VbUnit, NUnit, PyUnit, SQLUnit, XMLUnit, ...XUnit Online: www.xprogramming.com/software

JUnit Architecture

JUnit Testing

Regression, Modularity, Simplicity“Keep the bar green to keep the code clean”SimpleTest Example

Class declaration and Constructorimport java.util.*; import junit.framework.*;

public class SimpleTest extends TestCase { public SimpleTest(String name) {

super(name);}

}

JUnit Testing

SimpleTest ExampleDeclaring a test method

Creating a test suite

public static Test suite() { return new TestSuite(SimpleTest.class);

}

public void testEmptyCollection() { Collection collection = new ArrayList(); assertTrue(collection.isEmpty());

}

JUnit Testing

SimpleTest ExampleTest execution

public static void main(String args[]) { junit.textui.TestRunner.run(suite());//junit.swingui.TestRunner.run(suite());

}

JUnit TestingTestCase (descends from Assert, implements Test)

Setup()TearDown()assertEquals()assertFalse(), assertTrue()assertSame(), assertNotSame()fail()

TestSuiteaddTest(Test)

JUnit Testing

Demonstration

JUnit TestingTesting Exceptions (expected and unexpected)

public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); try {

Object o = emptyList.get(0); fail("Should raise an IndexOutOfBoundsException");

} catch (IndexOutOfBoundsException success) {}

}

public void testIndexOutOfBoundsExceptionNotRaised() throws IndexOutOfBoundsException { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0);

}

NUnit – xUnit for .NETUnit-testing framework for all .Net languages.Initially ported from JUnit, the current version, 2.1 is

the third major release of this xUnit based unittesting tool for Microsoft .NET. It is written entirely in C# and has been completelyredesigned to take advantage of many .NET language features, for example custom attributesand other reflection related capabilities. NUnit brings xUnit to all .NET languages.

NUnit – xUnit for .NET

AttributesTestFixture (instead of TestCase)TestSetup()/Teardown()Expected ExceptionSuiteIgnore

NUnit – xUnit for .NET

TestFixtureC# VB.NET

namespace NUnit.Tests { using System; using NUnit.Framework;

[TestFixture] public class SuccessTests {

// ... }

}

Imports SystemImports Nunit.Framework

Namespace Nunit.Tests

<TestFixture()> Public Class SuccessTests' ...

End ClassEnd Namespace

NUnit – xUnit for .NET

Testnamespace NUnit.Tests { using System; using NUnit.Framework;

[TestFixture] public class SuccessTests {

[Test] public void Add() { /* ... */

} public void TestSubtract() {

/* backwards compatibility*/

} }

}

Imports SystemImports Nunit.Framework

Namespace Nunit.Tests

<TestFixture()> Public Class SuccessTests<Test()> Public Sub Add()

' ... End SubPublic Sub testAdd()

‘ backwards compatibilityEnd Sub

End Class

End Namespace

NUnit – xUnit for .NET

Setup/TearDown (C#) (I)namespace NUnit.Tests { using System; using NUnit.Framework;

[TestFixture] public class SuccessTests {

[TestFixtureSetUp] public void Init() { /* ... */

} [TestFixtureTearDown] public void Dispose() {

/* ... */ } [Test] public void Add() { /* ... */ }

} }

NUnit – xUnit for .NET

Setup/TearDown (C#) (II)namespace NUnit.Tests {

using System; using NUnit.Framework;

[TestFixture] public class SuccessTests { [SetUp] public void Init() {

/* ... */ } [TearDown] public void Dispose() {

/* ... */ } [Test] public void Add() {

/* ... */ } }

}

NUnit – xUnit for .NET

Expected Exception (C#)namespace NUnit.Tests {

using System; using NUnit.Framework;

[TestFixture] public class SuccessTests {

[Test] [ExpectedException(typeof(InvalidOperationException))] public void ExpectAnException() {

/* ... */ }

} }

NUnit – xUnit for .NET

Expected Exception (VB.NET)

Imports SystemImports Nunit.Framework

Namespace Nunit.Tests

<TestFixture()> Public Class SuccessTests<Test(), ExpectedException(GetType(Exception))> Public Sub ExpectAnException()

' ... End Sub

End ClassEnd Namespace

NUnit – xUnit for .NET

Suite (C#) namespace NUnit.Tests { using System; using NUnit.Framework;

public class AllTests { [Suite] public static TestSuite Suite {

get { TestSuite suite = new TestSuite("All Tests"); suite.Add(new OneTestCase()); suite.Add(new Assemblies.AssemblyTests()); suite.Add(new AssertionTest()); return suite;

} }

} }

NUnit – xUnit for .NET

IgnoreC# VB.NET

namespace NUnit.Tests { using System; using NUnit.Framework;

[TestFixture] [Ignore("Ignore a fixture")] public class SuccessTests {

// ... }

}

Imports SystemImports Nunit.Framework

Namespace Nunit.Tests

<TestFixture(), Ignore("Ignore a fixture")> Public Class SuccessTests

' ... End Class

End Namespace

NUnit – xUnit for .NET

Demonstration

Mock ObjectsMock objects make it possible to test an objectwithout its knowledge. keep stub testing coding out of the real classCharacteristics:

is easily created is easily set up is quick is deterministic has easily caused behaviourhas no direct user interface is directly queriable

Mock Objects

ApplicationsUnit test your application independently of theproduction infrastructure.Anticipate a set of preconditions andpostconditionsDevelopers do not need access to a real database to run the unit tests.Simulate states that may be difficult or time-consuming to realize in a runtime environment.

Mock Objects

ExampleAsserting the right calling order

Mock ClassPublic class MyMockObject extends MyObject {

public boolean methodCalled = false;protected boolean propagateChanges = false;public void mockMethod(int args) {

if (propagateChanges) {//call parent method

}methodCalled = true;

}}

Mock Objects

Test Class [TestFixture] public class TestClass {MyMockObject mock;[Setup] public void Init() {

mock = new MyMockObject();}

[Test] public void testRightProcCalling() {// trigger calling…assertTrue(mock.methodCalled);

}[Test] public void testProcFunc() {

mock.propagateEvents = true;// trigger calling…// assert funcionality

}}

ApontadoresExtreme Programming

www.extrememprogramming.orgwww.xprogramming.com

JUnitwww.junit.org

NUnitwww.nunit.orgnunit.sourceforge.org

Mock Objectswww.mockobjects.com

Referências“Endo-Testing: Unit Testing with MockObjects”Tim Mackinnon, Steve Freeman, PhilipCraig 2000“XUnit Testing – A plea for assertEquals” Tim Mackinnon“Test Infected – Programmers Love WritingTests” Erich Gamma, Kent Beck, online athttp://junit.sourceforge.net/doc/testinfected/testing.htmJUnit.org website, online at http://www.junit.orgNUnit.org website, online at http://www.nunit.orgwww.extremeprogramming.org site

Referências

“Extreme Programming explained: Embrace Change”. Kent Beck, Addison-Wesley, 1999

Recommended