проблема запуска тестов JUnit с Ant в Eclipse.Вопрос новичка - PullRequest
1 голос
/ 25 сентября 2011

В эти дни я учусь тому, как использовать ant для запуска автоматического теста, следуя этому учебнику .

У меня есть JUnit в classpath моего проекта. Кажется, все работает нормально, и я могу включить это в свои классы:

import junit.framework.TestCase; //line20

public class SimpleLattice1DTest extends TestCase{
 ...
}

Мой build.xml:

<?xml version="1.0"?>
<project name="Ant-Test" default="compile" basedir=".">
    <!-- Sets variables which can later be used. -->
    <!-- The value of a property is accessed via ${} -->
    <property name="src.dir" location="." />
    <property name="build.dir" location="build" />
    <property name="dist.dir" location="dist" />
    <property name="docs.dir" location="docs" />
    <property name="test.dir" location="jlife/tests" />
    <property name="test.report.dir" location="test/report" />  

    <!-- Deletes the existing build, docs and dist directory-->
    <target name="clean">
        <delete dir="${build.dir}" />
        <delete dir="${docs.dir}" />
        <delete dir="${dist.dir}" />
    </target>

    <!-- Creates the  build, docs and dist directory-->
    <target name="makedir">
        <mkdir dir="${build.dir}" />
        <mkdir dir="${docs.dir}" />
        <mkdir dir="${dist.dir}" />

        <mkdir dir="${test.report.dir}" />


    </target>

    <!-- Compiles the java code (including the usage of library for JUnit -->
    <target name="compile" depends="clean, makedir">
        <javac srcdir="${src.dir}" destdir="${build.dir}">
        </javac>

    </target>

    <!-- Creates Javadoc -->
    <target name="docs" depends="compile">
        <javadoc packagenames="src" sourcepath="${src.dir}" destdir="${docs.dir}">
            <!-- Define which files / directory should get included, we include all -->
            <fileset dir="${src.dir}">
                <include name="**" />
            </fileset>
        </javadoc>
    </target>

    <!--Creates the deployable jar file  -->
    <target name="jar" depends="compile">
        <jar destfile="${dist.dir}\CoreTest.jar" basedir="${build.dir}">
            <manifest>
                <attribute name="Main-Test" value="test.CoreTest" />
            </manifest>
        </jar>
    </target>


    <!-- Run the JUnit Tests -->
        <!-- Output is XML, could also be plain-->
        <target name="junit" depends="compile">
            <junit printsummary="on" fork="true" haltonfailure="yes">

                <formatter type="xml" />
                <batchtest todir="${test.report.dir}">
                    <fileset dir="${src.dir}">
                        <include name="**/*Test*.java" />
                    </fileset>
                </batchtest>
            </junit>
        </target>

</project>

Когда я запускаю его в затмении, я получаю следующую ошибку:

[javac] C: \ Documents and Настройки \ Noname \ Documenti \ JLife_git \ JLife_git \ JLife \ SRC \ jlife \ Тесты \ SimpleLattice1DTest.java: 20: пакет junit.framework не существует [javac] import junit.framework.TestCase;

Полагаю, с этим что-то не так, но я понятия не имею. Может ли кто-нибудь направить меня в правильном направлении?

Ответы [ 4 ]

2 голосов
/ 25 сентября 2011

Ваша цель javac не указывает ничего, кроме исходного и целевого каталога - она ​​не добавляет никаких записей пути к классам;вам нужно будет добавить запись для соответствующего JAR-файла JUnit.См. javac документацию к заданию для получения более подробной информации.Возможно, вы захотите указать путь к JUnit в виде атрибута classpath, вложенного элемента или ссылки на путь, объявленный в другом месте.

1 голос
/ 25 сентября 2011

Путь к классу eclipse отделен от среды вашего муравья.В вашем файле сборки, когда вы вызываете javac, вам необходимо указать атрибут classpath.

Вы можете определить classpath вверху файла с остальными вашими свойствами, например:

<path id="classpath">
    <fileset dir="[path to libraries]" includes="**/*.jar" />
</path>

, а затем используйте его при каждом вызове javac, установив атрибут classpathref, например:

<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="classpath" />
1 голос
/ 25 сентября 2011

Вам необходимо указать каталог, в котором содержатся ваши файлы .class и ваши внешние jar-файлы (например, junit).

например,

<!-- Populates a class path containing our classes and jars -->
<path id="dist.classpath">
    <fileset dir="${lib}"/>
    <pathelement path="${build}"/>
</path>
<!-- Compile the java code place into ${build} -->
<target name="compile" depends="-dirty" description="Compile the source.">
    <javac srcdir="${source}" destdir="${build}" includeantruntime="false">
        <classpath refid="dist.classpath"/>
        <exclude name="${test.relative}/**/*"/>
    </javac>
</target>

Вот полный файл, который я взял, отрывок из которогоНа случай, если вам нужны идеи, как настроить другие общие вещи (emma, javadoc и т. д.)

<project name="imp" default="dist" basedir="..">

<description>Buildscript for IMP</description>

<property name="source" location="src"/>
<property name="lib"  location="lib"/>
<property name="history" location="test_history"/>
<property name="web-tests" location="/var/www/tests"/>
<property name="web-files" location="/var/www/files"/>
<property name="web-javadoc" location="/var/www/javadoc"/>
<property name="web-emma" location="/var/www/emma"/>
<property name="emma.dir" value="${lib}"/>
<property name="test" location="${source}/imp/unittest"/>
<property name="test.relative" value="imp/unittest"/>
<property name="javadoc-theme" value="tools/javadoc-theme"/>

<!-- directories for generated files -->
<property name="build" location="build"/>
<property name="build-debug" location="debug"/>
<property name="build-coverage" location="coverage"/>
<property name="dist"  location="dist"/>
<property name="reports" location="reports"/>
<property name="coverage-emma" location="${reports}/coverage/emma"/>

<!-- Populates a class path containing our classes and jars -->
<path id="dist.classpath">
    <fileset dir="${lib}"/>
    <pathelement path="${build}"/>
</path>
<path id="debug.classpath">
    <fileset dir="${lib}"/>
    <pathelement path="${build-debug}"/>
</path>

<!-- import emma. This classpath limits the coverage to just our classes -->
<path id="debug.imp.classpath">
    <pathelement path="${build-debug}"/>
</path>
<taskdef resource="emma_ant.properties" classpathref="debug.classpath"/>

<!-- 
    Shouldn't ever need to use this from the command line. IRC saith that the "private"
    internal use only sort of targets are prefixed with '-'. 
    dirty because it's the opposite of the 'clean' target.
-->
<target name="-dirty">
    <tstamp/>
    <mkdir dir="${build}"/>
    <mkdir dir="${build-debug}"/>
    <mkdir dir="${build-coverage}"/>
    <mkdir dir="${dist}"/>
    <mkdir dir="${reports}"/>
    <mkdir dir="${coverage-emma}"/>
</target>

<!-- clean up all the generated files and direcories -->
<target name="clean" description="Deletes all files and directories created by this script.">
    <delete dir="${build}"/>
    <delete dir="${build-debug}"/>
    <delete dir="${build-coverage}"/>
    <delete dir="${dist}"/>
    <delete dir="${reports}"/>
    <delete dir="${coverage-emma}"/>
</target>

<!-- Compile the java code place into ${build} -->
<target name="compile" depends="-dirty" description="Compile the source.">
    <javac srcdir="${source}" destdir="${build}" includeantruntime="false">
        <classpath refid="dist.classpath"/>
        <exclude name="${test.relative}/**/*"/>
    </javac>
</target>

<!-- Compile the java code with debug info place into ${build} -->
<target name="compile-debug" depends="-dirty" description="Compile the source with debug information.">
    <javac
        srcdir="${source}"
        destdir="${build-debug}"
        includeantruntime="false"
        debug="true"
        debuglevel="lines,vars,source"
    >
        <classpath refid="debug.classpath"/>
    </javac>
</target>

<!-- roll up everyting into a single jar file -->
<target name="dist" depends="clean, compile" description="Generate the distribution file for IMP.">
    <!-- Copy the library .jars to the directory where the IMP distribution will be located -->
    <copy todir="${dist}">
        <fileset dir="${lib}"/>
    </copy>

    <!-- TODO: Generate the MANIFEST.MF file on the fly -->
    <jar jarfile="${dist}/imp.jar" basedir="${build}" manifest="tools/MANIFEST.MF"/>

    <!-- dump to web server -->
    <copy todir="${web-files}">
        <fileset dir="${dist}"/>
    </copy>
</target>

<!-- build and run the tests then report the results in HTML -->
<target name="test" depends="compile-debug" description="Run all the JUnit tests and outputs the results as HTML.">
    <!-- run the tests -->
    <junit printsummary="true" haltonerror="false" haltonfailure="false">
        <classpath refid="debug.classpath"/>
        <formatter type="xml"/>
        <batchtest fork="true" todir="${reports}">
            <fileset dir="${source}">
                <include name="${test.relative}/**/*Test*.java"/>
                <exclude name="${test.relative}/**/AllTests.java"/>
            </fileset>
        </batchtest>
    </junit>

    <!-- report the results -->
    <junitreport todir="${reports}">
        <fileset dir="${reports}" includes="TEST-*.xml"/>
        <report todir="${reports}"/>
    </junitreport>

    <!-- update the latest results file to be commited -->
    <copy file="${reports}/TESTS-TestSuites.xml" tofile="${history}/test-results-latest.xml"/>

    <!-- dump to webserver -->
    <copy todir="${web-tests}">
        <fileset dir="${reports}"/>
    </copy>
</target>

<!-- run emma code coverage tool and publish results in HTML -->
<target name="emma" depends="compile-debug"  description="Checks code coverage with Emma.">
    <!-- put the magic emma juice into the classes -->
    <emma>
        <instr
            instrpathref="debug.imp.classpath"
            destdir="${coverage-emma}/instr"
            metadatafile="${coverage-emma}/metadata.emma"
            merge="true"
        />
    </emma>

    <!-- run the tests -->
    <junit fork="true" printsummary="true" haltonerror="false" haltonfailure="false">
        <classpath>
            <pathelement location="${coverage-emma}/instr"/>
            <path refid="debug.classpath"/>
        </classpath>
        <batchtest fork="true" todir="${reports}">
            <fileset dir="${source}">
                <include name="${test.relative}/**/*Test*.java"/>
                <exclude name="${test.relative}/**/AllTests.java"/>
            </fileset>
        </batchtest>
        <jvmarg value="-Demma.coverage.out.file=${coverage-emma}/coverage.emma"/>
        <jvmarg value="-Demma.coverage.out.merge=true"/>
    </junit>

    <!-- publish the coverage report -->
    <emma>
        <report sourcepath="${source}" verbosity="verbose">
            <fileset dir="${coverage-emma}">
                <include name="*.emma"/>
            </fileset>

            <html outfile="${web-emma}/index.html"/>
        </report>
    </emma>
</target>

<!-- publish javadoc -->
<target name="javadoc" description="Creates javadoc for IMP.">
    <delete dir="${web-javadoc}"/>
    <javadoc
            sourcepath="${source}"
            defaultexcludes="no"
            destdir="${web-javadoc}"
            author="true"
            version="true"
            use="true"
            windowtitle="IMP: Integrated Mechanisms Program"
            overview="${source}/overview.html"
            classpathref="debug.classpath"
            stylesheetfile="${javadoc-theme}/stylesheet.css"
    />
    <copy file="${javadoc-theme}/javadoc.jpg" tofile="${web-javadoc}/javadoc.jpg"/>
</target>

<target name="all" description="Runs test, emma, javadoc, and dist targets.">
    <antcall target="test"/>
    <antcall target="emma"/>
    <antcall target="javadoc"/>
    <antcall target="dist"/>
</target>

</project>
0 голосов
/ 31 января 2012

Если вы наблюдаете стек ошибок, вы найдете следующую строку, чуть выше указанной вами строки ошибки ...

[javac] [путь поиска для файлов классов: C: \ Program Files \ Java\ jre6 \ lib \ resource ...

В этой строке отображаются все jar-файлы, доступные в пути к классам для выполнения целевого объекта ant.Вы определенно не найдете здесь нужную банку, т.е. junit-xxxjar (junit-4.8.2.jar)

Теперь перейдите к затмению -> Окно -> Настройки -> Муравей -> Время выполнения -> Глобальные записи -> Добавить Jars add junit-4.8.2jar (который вы найдете в каталоге lib вашего проекта)

Если вы поиграете с Ant -> Runtime -> classpath и строкой ошибки, связанной с classpath в стеке ошибок, выпоймет проблему.

Надеюсь, что это решит вашу проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...