« Snipe Flies | Main | Blowfly »
Friday
Jun292012

Unit Test Examples

Here is a set of simple unit tests in various programming languages.  Each one performs two tests on the string length function. They are intended as simple examples of how to get started unit testing.

This was partly inspired by a blog post by Mike Clarke,

Ruby (string_test.rb)

require 'test/unit'
class StringTest < Test::Unit::TestCase
  def test_length_of_empty_string
    assert_equal(0, "".length)
  end
  def test_length_of_nonempty_string
    s = "abcd"
    assert_equal(4, s.length)
  end
end

PHP (string_test.php)

<?php
require_once 'PHPUnit/Autoload.php';
class String_Test extends PHPUnit_Framework_TestCase
{
	public function test_length_of_empty_string() {
		$this->assertEquals(0, strlen(''));
	}
	public function test_length_of_nonempty_string() {
		$this->assertEquals(4, strlen('abcd'));
	}
}
// End of file

Python (string_test.py)

import unittest
class StringTest(unittest.TestCase):
  def testLengthOfEmptyString(self):
    self.assertEquals(len(""), 0)
  def testLengthOfNonEmptyString(self):
    self.assertEquals(len("abcd"), 4)
if __name__ == '__main__':
  unittest.main()

Haskell (string_test.hs)

import Test.HUnit
test1 :: Test
test1 = TestCase (assertEqual "Length of Empty String" 0 (length ""))
test2 :: Test
test2 = TestCase (assertEqual "Length of Nonempty String" 4 (length "abcd"))
compositeTest :: Test
compositeTest = TestList [TestLabel "test1" test1, TestLabel "test2" test2]
main :: IO ()
main = do
         _ <- runTestTT compositeTest
         return ()

Java (StringTest.java)

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StringTest {
	@Test
	public void testLengthOfEmptyString() {
		assertEquals("LengthOfEmptyString", 0, "".length());
	}
	@Test
	public void testLengthOfNonemptyString() {
		assertEquals("LengthOfNonemptyString", 4, "abcd".length());
	}
}

Now a Bash script to run them all. This was written for my particular Ubuntu 10.04 LTS setup. You might need to modify it for other setups and other operating systems.

#!/bin/bash
rule="======================================================================"
echo $rule
echo "RUBY:"
ruby string_test.rb
echo $rule
echo "PHP:"
phpunit string_test.php
echo $rule
echo "PYTHON:"
python string_test.py
echo $rule
echo "HASKELL:"
runhaskell string_test.hs
echo $rule
echo "JAVA:"
javac -cp /usr/share/java/junit4.jar StringTest.java
java -cp /usr/share/java/junit4.jar:. org.junit.runner.JUnitCore StringTest
echo $rule

Running this script gives the following output:

======================================================================
RUBY:
Loaded suite string_test
Started
..
Finished in 0.00063 seconds.

2 tests, 2 assertions, 0 failures, 0 errors
======================================================================
PHP:
PHPUnit 3.6.10 by Sebastian Bergmann.

..

Time: 0 seconds, Memory: 2.75Mb

OK (2 tests, 2 assertions)
======================================================================
PYTHON:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
======================================================================
HASKELL:
Cases: 2  Tried: 2  Errors: 0  Failures: 0
======================================================================
JAVA:
JUnit version 4.8.1
..
Time: 0.013

OK (2 tests)

======================================================================

In order to test the tests I reran the script after editing each test file to change the expected length of the nonempty string from 5 to 4 (without changing the nonempty string itself). This gave the following output:

======================================================================
RUBY:
Loaded suite string_test
Started
.F
Finished in 0.025308 seconds.

  1) Failure:
test_length_of_nonempty_string(StringTest) [string_test.rb:11]:
<5> expected but was
<4>.

2 tests, 2 assertions, 1 failures, 0 errors
======================================================================
PHP:
PHPUnit 3.6.10 by Sebastian Bergmann.

.F

Time: 0 seconds, Memory: 2.75Mb

There was 1 failure:

1) String_Test::test_length_of_nonempty_string
Failed asserting that 4 matches expected 5.

/home/tristram/Desktop/learn-by-test/string_test.php:13

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
======================================================================
PYTHON:
.F
======================================================================
FAIL: testLengthOfNonEmptyString (__main__.StringTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "string_test.py", line 9, in testLengthOfNonEmptyString
    self.assertEquals(len("abcd"), 5)
AssertionError: 4 != 5

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=1)
======================================================================
HASKELL:
### Failure in: 1:test2
Length of Nonempty String
expected: 5
 but got: 4
Cases: 2  Tried: 2  Errors: 0  Failures: 1
======================================================================
JAVA:
JUnit version 4.8.1
..E
Time: 0.017
There was 1 failure:
1) testLengthOfNonemptyString(StringTest)
java.lang.AssertionError: LengthOfNonemptyString expected:<5> but was:<4>
	at org.junit.Assert.fail(Assert.java:91)
	at org.junit.Assert.failNotEquals(Assert.java:645)
	at org.junit.Assert.assertEquals(Assert.java:126)
	at org.junit.Assert.assertEquals(Assert.java:470)
	at StringTest.testLengthOfNonemptyString(StringTest.java:14)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.junit.runners.Suite.runChild(Suite.java:128)
	at org.junit.runners.Suite.runChild(Suite.java:24)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:136)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
	at org.junit.runner.JUnitCore.runMain(JUnitCore.java:98)
	at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:53)
	at org.junit.runner.JUnitCore.main(JUnitCore.java:45)

FAILURES!!!
Tests run: 2,  Failures: 1

======================================================================

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.