Искал в интернете как настроить
Emma под Weblogic, ничего конкретного не находил, только общие правила. И так постараюсь описать по пунктам что нужно сделать, если кому будет, что добавить или меня поправить обращайтесь.
Я пользуюсь системой сборки ant.
1. Настроим build.xml.
Для этого в build.xml напишем следующее:
Код |
<project name = "test_implementation" default = "emma.instr"> <description>Unit testing system.</description> <import file = "${basedir}/../source/build.xml"/> <target name = "compile-tests" depends = "test-init" description = "Compile tests."> <mkdir dir = "${test.compile.dir}"/> <javac debug = "true" debuglevel = "lines,source" fork = "yes" destdir = "${test.compile.dir}" executable = "${JAVA_HOME}/bin/javac" source = "1.5"> <src path = "${test.src.dir}"/> <src path = "${project.src.dir}"/> <classpath refid = "test.lib.path"/> <classpath refid = "wl_path"/> <classpath refid = "proprietary_path"/> <classpath refid = "third_party_path"/> </javac> <path id = "build.classpath"> <pathelement path = "${test.compile.dir}"/> </path> </target> <target name = "test-init" description = "Target initiates basic pathes and properties, makes necessary directories."> <property name = "project.src.dir" location = "${basedir}/../source"/> <property name = "config.dir" location = "${project.src.dir}"/> <property file = "${config.dir}/build.properties"/> <property name = "test.src.dir" value = "${basedir}/sources"/> <property name = "test.lib.dir" value = "${basedir}/lib"/> <property name = "test.output.dir" value = "${BASE_OUTPUT_DIR}/test"/> <property name = "test.rawreport.dir" value = "${test.output.dir}/rawtestoutput"/> <property name = "test.output.htmlreport.dir" value = "${test.output.dir}/test-reports"/> <property name = "test.compile.dir" value = "${test.output.dir}/test-classes"/> <path id = "test.lib.path"> <fileset dir = "${test.lib.dir}"> <include name = "*.jar"/> </fileset> </path> <mkdir dir = "${test.output.dir}"/> <mkdir dir = "${test.rawreport.dir}"/> </target> <target name = "emma.instr" depends = "compile-tests, emma.init" if = "emma.enabled"> <emma> <instr instrpathref = "build.classpath" destdir = "${emma.instr.dir}" metadatafile = "${emma.output.dir}/metadata.emma" merge = "true"> <filter includes = "package_name1.*"/> <filter excludes = "package_name2.*"/> <filter excludes = "*class_name*"/> <filter excludes = "*Response*"/> <filter excludes = "*Test*"/> <filter excludes = "*.class_name1*, *.class_name2*"/> <filter includes = "package_name3.*"/> </instr> </emma> </target> <target name = "emma.init"> <property name = "emma.enabled" value = "true"/> <path id = "emma.lib"> <pathelement location = "${test.lib.dir}/emma.jar"/> <pathelement location = "${test.lib.dir}/emma_ant.jar"/> </path> <taskdef resource = "emma_ant.properties" classpathref = "emma.lib"/> <property name = "emma.enabled" value = "true"/> <property name = "emma.coverage.dir" value = "${test.output.dir}/coverage"/> <mkdir dir = "${emma.coverage.dir}"/> <property name = "emma.instr.dir" value = "${test.output.dir}/instr"/> <mkdir dir = "${emma.instr.dir}"/> <property name = "emma.output.dir" value = "${test.output.dir}/emma"/> <mkdir dir = "${emma.output.dir}"/> </target> </project>
|
Самое важное находится в таске "
emma.instr". Фильтры определяют максимальный coverage.
2. Сбилдим таску "
emma.instr". В результате билда, должно появится:
2.1. Файл
metadata.emma в директории
emma.output.dir.
2.2. Сгенеренные классы в директории
emma.instr.dir - это классы которые мы собираемся тестить, но с метками для Emma. В последствии мы их подложем на сервер вместо Source файлов.
3. Переносим emma.jar и objenesis.jar, junit.jar, jmock-legacy.jar, jmock-junit4.jar, jmock.jar, hamcrest-library.jar, hamcrest-core.jar, cglib-nodep-2.jar в lib директорию сервера(classpath).
4. В config.xml сервера в аргументы ноды прописываем “-Demma.coverage.out.merge=true”(я на одной ноде кластерного сервера делал).
5. Копируем/перетираем сорсы на сорсы из папки
emma.instr.dir в соответсвующую папку на сервере.
6. пишем JSP/ class и деплоим на сервер(отмечу это под emma версии 2.0.5):
Код |
package com.test;
import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import com.vladium.emma.data.CoverageOptions; import com.vladium.emma.data.CoverageOptionsFactory; import com.vladium.emma.rt.RT; import java.io.File; import java.util.Properties;
public class Run {
private List junitTests = new ArrayList(1000); private Result re = null; private StringBuilder print = new StringBuilder(); int i = 0; int iFailures = 0; Properties toolProperties = new Properties(); final CoverageOptions options = CoverageOptionsFactory.create(toolProperties);
public static void main(String... arg) throws Exception { Run run = new Run(); run.init(); run.execute(); File ecFile = new File(System.getProperty("user.dir") + "/coverage.ec"); RT.dumpCoverageData(ecFile, true, false); //это чудо строчечка сгенерит на файл о пройденных тестах, без нее ни куда((
}
protected void init() throws IOException { JarFile fl = new JarFile(System.getProperty("user.dir") + "/JUnitTests.jar"); // В этом JAR лежат все необходимые мне JUnit тесты и я динамически подгружаю все тесты, прогресс не стоит на месте Enumeration<JarEntry> entries = fl.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (!entry.isDirectory() && name.contains("Test.class") && !name.contains("RunTest.class") && !name.contains("$")) { junitTests.add(name.replace('/', '.').substring(0, name.length() - 6)); } } }
protected Class[] loadClasses(List classes) { Class[] cls = new Class[classes.size()]; for (int j = 1; j <= classes.size(); ++j) { try { cls[j - 1] = Class.forName((String) classes.get(j - 1)); } catch (Exception e) { continue; } } return cls; }
protected void execute() { CharSequence cs1 = ";"; CharSequence cs2 = ";<br/>";
Class[] classes = loadClasses(junitTests); for (Class cl : classes) { try { re = org.junit.runner.JUnitCore.runClasses(cl); print.append("Run: " + cl.getName()).append("<br/>"); i += re.getRunCount(); List<Failure> failures = re.getFailures(); for (Failure failure : failures) {
print.append(" <b>Test is failed:</b> ").append(failure.getTestHeader()); print.append(". <b>Message is :</b>" + failure.getMessage()); print.append(". </br><b>Exception is :</b>" + failure.getException().toString().replace(cs1, cs2)); print.append(". </br><b>Trace is :</b>" + failure.getTrace().replace(cs1, cs2)); print.append("</br>"); print.append("</br>"); ++iFailures; } } catch (Exception e) { ++iFailures; print.append(" </br><b>Error occured:</b>").append(e.toString().replace(cs1, cs2)); print.append("</br>"); print.append("</br>"); } }
}
/** * @return the print */ public String getPrint() { return print.toString(); } }
|
7. Запустили класс/JSP.
8. Скопировали файл "coverage.ec" в директорию к metadate.emma
9. Запускаем не сложную команду и хлопаем в ладоши:
Код |
java “classpath/emma.jar” emma report -r html -in metadata.emma,coverage.ec -Dreport.html.out.file=coverage/coverage.html
|