Home > java > Converting jUnit test to TestNG tests.

Converting jUnit test to TestNG tests.

Update

After writing the below script, and submitting my change for a code review, the reviewer pointed me to a TestNG provided tool that will convert them. So here it is:

java org.testng.JUnitConverter -overwrite -annotation -srcdir src

Be sure to include the testng jar, along with the $JAVA_HOME/lib/tools.jar in your classpath when you run that.

Original SED way of converting

Because of the exceptional design of TestNG, this is a pretty simple text replace exercise. Here is a shell script using sed that will do most of the work for you. After it runs, just remove jUnit from your dependency list / classpath and re-compile, hand edit any errors.

There are two steps to running this, first, create a list of all the java files that contain junit references in your src.

find . -name "*.java" | xargs grep -L junit > toconvert

Then, use xargs to run the script on all the files.

cat toconvert | xargs testngify

Here is the contents of the testngify shell script:


#!/bin/bash

IN_FILE=$1
function replace {
OUT_FILE="${IN_FILE}'.tmp'"
#echo executing pattern: $1
sed "$1" < $IN_FILE > $OUT_FILE
rm $IN_FILE
mv $OUT_FILE $IN_FILE
}

replace "s/import org\.junit\.After;/import org\.testng\.annotations\.AfterMethod;/g"
replace "s/import org\.junit\.Assert;/import org\.testng\.AssertJUnit;/g"
replace "s/import org\.junit\.Before;/import org\.testng\.annotations\.BeforeMethod;/g"
replace "s/import org\.junit\.Test;/import org\.testng\.annotations\.Test;/g"
replace "s/import junit\.framework\.Assert;/import org\.testng\.AssertJUnit;/g"
replace "s/import\s*static\s*org\.junit\.Assert\.\*;/import static org\.testng\.AssertJUnit\.\*;/g"
replace "s/import\s*static\s*org\.junit\.Assert\.assertEquals;/import static org\.testng\.AssertJUnit\.assertEquals;/g"
replace "s/\(\s\)Assert\./\1AssertJUnit\./g"
replace "s/import org\.junit\.Test;/import org\.testng\.annotations\.Test;/g"
replace "s/\(@Test\s*\)(expected\s*=/\1(expectedExceptions =/g"
replace "s/\(@Test\.*\)ComparisonFailure\.class/\1AssertionError\.class/g"
replace "s/@After\s*$/@AfterMethod/g"
replace "s/@Before\s*$/@BeforeMethod/g"
replace "s/@Before()\s*$/@BeforeMethod/g"
replace "s/org\.junit\.Assert\./org.testng.AssertJUnit\./g"
replace "s/.*@Ignore(\"\(.*\)\")/\t@Test(enabled=false) \/\/\1/g"
replace "s/\(.*\)@Ignore\(.*\)/\1\2/g"
replace "s/^.*org\.junit.*$//g"

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
Categories: java Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.