Skip to content

Instantly share code, notes, and snippets.

@has207
Created July 22, 2013 02:05
Show Gist options
  • Save has207/6050885 to your computer and use it in GitHub Desktop.
Save has207/6050885 to your computer and use it in GitHub Desktop.
Convert JUnit3 tests to JUnit4
# save class annotation to the clipboard
/^@MediumTest/ {
h
d
}
/^@LargeTest/ {
h
d
}
# remove duplicate annotations
/^\ \ @MediumTest/ {
x
/@MediumTest/ {
x
d
b delMediumDone
}
x
:delMediumDone
}
/^\ \ @LargeTest/ {
x
/@LargeTest/ {
x
d
b delLargeDone
}
x
:delLargeDone
}
/^\ \ @SmallTest/d
# replace annotation on setUp/tearDown
/\ \ @Override\ p/ {
# Override is on the same line
b setUpTearDown
}
/\ \ @Override$/ {
# Override is on its own line
N
:setUpTearDown
/\ void\ setUp/ {
b setUp
}
/\ void\ tearDown/ {
b tearDown
}
}
# this block never matches / only contains labels
/$^/ {
:setUp
s/Override/Before/
s/protected/public/
b done
:tearDown
s/Override/After/
s/protected/public/
b done
:done
}
# Add the splat static import -- it will get expanded by Orgainize Imports later
/^package\ / {
a\
\
import static org.junit.Assert.*;
}
# probably not necessary to add this stuff since Organize Imports
# should add it anyway but what the hell
/^import\ junit.framework.TestCase/ {
i\
import org.junit.*;\
import org.junit.runner.RunWith;\
import org.junit.runners.JUnit4;
}
/^public\ class.*Test/ {
/Test$/ {
# fix up class declaration split across lines
N
}
i\
@RunWith(JUnit4.class)
s/^\(public\ class.*Test\).*extends.TestCase/\1/
}
# delete this to avoid duplication, we will add it in later
/^\ \ @Test$/ d
# add test annotations to the methods
/^\ \ public\ void\ test/ {
x
/^@MediumTest/ {
b insertAnnotate
}
/^@LargeTest/ {
b insertAnnotate
}
/$^/ {
:insertAnnotate
s/^/\ \ /
p
s/^\ \ //
x
b doneInsertAnnotate
}
x
:doneInsertAnnotate
i\
@Test
}
# fix up setUp/tearDown methods, removing them if they're empty
/\ setUp.*{$/ {
N
/super\.setUp()/ {
N
s/\n[^\n]*super\.setUp()[^\n]*//
/{\n\ \ }/d
}
}
/\ tearDown.*{$/ {
N
/super\.tearDown()/ {
N
s/\n[^\n]*super\.tearDown()[^\n]*//
/{\n\ \ }/d
}
}
# delete super calls in case they were not the first/only line in setUp/tearDown
/super\.setUp()/d
/super\.tearDown()/d
@has207
Copy link
Author

has207 commented Jul 22, 2013

#!/usr/bin/bash
# Run the sed script on all tests in current directory and use vim + eclim to fix up imports

for file in *Test.java; do
    if ! $(grep -q @RunWith.JUnit4 "$file"); then
        sed -i -f junit3to4.sed "$file";
        /usr/bin/vim "$file" +JavaImportOrganize +wq
    fi;
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment