如何在 Eclipse 中递归查找并运行所有 Junit 4 测试?

发布于 2024-09-18 21:54:59 字数 533 浏览 5 评论 0原文

我想在我的 Eclipse 项目中运行所有 junit 4 测试。该项目是使用 /source 和 /test 设置的。 /test 下是各种包,例如:

com.yaddayadda.test.core.entity
com.yaddayadda.test.core.framework

如果我在 Package Explorer 中的 /test 级别右键单击并选择 Run As; Junit 测试我收到错误:

No tests found with test runner 'JUnit 4'.

如果我右键单击 com.yaddayadda.test.core.entity,则会找到并运行该包中的所有测试。因此 @Test 注释是正确的(它们也被构建服务器上的 Ant 正确拾取)。但是,如果我尝试运行 com.yaddayadda.test.core 中的所有测试,那么它什么也找不到。

基本上,它似乎只看包装内的东西,而不是回避所有的孩子。有办法解决这个问题吗?

I would like to run all junit 4 tests within my Eclipse project. The project is setup with /source and /test. Under /test are various packages, such as:

com.yaddayadda.test.core.entity
com.yaddayadda.test.core.framework

If I right-click at the /test level in Package Explorer and choose Run As; Junit Test I receive the error:

No tests found with test runner 'JUnit 4'.

If I right-click on com.yaddayadda.test.core.entity, then it finds and runs all the tests within that package. So the @Test annotations are correct (they are also picked up by Ant correctly on the build server). However, if I try and run all tests within com.yaddayadda.test.core then it finds none.

Basically, it only seems to look within the package rather the recusively at all children. Is there a way to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一抹苦笑 2024-09-25 21:54:59

第一的:
在 Project Explorer 中选择您的项目,然后按 Alt+Shift+X T。它将运行该项目下的所有 JUint 测试。右键单击项目并选择“Run as”->JUnit test 也可以完成同样的操作。

如果这不起作用(很可能),请转到“运行/运行配置”,创建一个新的 JUnit 配置并告诉它运行项目中的所有测试。如果这不起作用,我需要先看看您的项目,然后才能提供帮助。

First:
Select your project in Project Explorer and press Alt+Shift+X T. It will run all the JUint tests under the project. The same can be done by right-clicking the project and selecting "Run as"->JUnit test.

If this does not work (which is likely), go to "Run/Run configurations", create a new JUnit configuration and tell it to run all the tests in your project. If this does not work, I'll need to have a look at your project before I can help.

晌融 2024-09-25 21:54:59

如果其他人正在寻找解决方案,我在 Burt Beckwith 的网站上找到了答案:

http:// /burtbeckwith.com/blog/?p=52

要使用它,只需在 Eclipse 的类树中右键单击它,然后单击“Run As JUnit Test”即可。

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;
import org.junit.internal.runners.InitializationError;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Suite;

/**
 * Discovers all JUnit tests and runs them in a suite.
 */
@RunWith(AllTests.AllTestsRunner.class)
public final class AllTests {

  private static final File CLASSES_DIR = findClassesDir();

  private AllTests() {
    // static only
  }

  /**
   * Finds and runs tests.
   */
  public static class AllTestsRunner extends Suite {

    private final Logger _log = Logger.getLogger(getClass());

    /**
     * Constructor.
     *
     * @param clazz  the suite class - <code>AllTests</code>
     * @throws InitializationError  if there's a problem
     */
    public AllTestsRunner(final Class<?> clazz) throws InitializationError {
      super(clazz, findClasses());
    }

    /**
     * {@inheritDoc}
     * @see org.junit.runners.Suite#run(org.junit.runner.notification.RunNotifier)
     */
    @Override
    public void run(final RunNotifier notifier) {
      initializeBeforeTests();

      notifier.addListener(new RunListener() {
        @Override
        public void testStarted(final Description description) {
          if (_log.isTraceEnabled()) {
            _log.trace("Before test " + description.getDisplayName());
          }
        }

        @Override
        public void testFinished(final Description description) {
          if (_log.isTraceEnabled()) {
            _log.trace("After test " + description.getDisplayName());
          }
        }
      });

      super.run(notifier);
    }

    private static Class<?>[] findClasses() {
      List<File> classFiles = new ArrayList<File>();
      findClasses(classFiles, CLASSES_DIR);
      List<Class<?>> classes = convertToClasses(classFiles, CLASSES_DIR);
      return classes.toArray(new Class[classes.size()]);
    }

    private static void initializeBeforeTests() {
      // do one-time initialization here
    }

    private static List<Class<?>> convertToClasses(
        final List<File> classFiles, final File classesDir) {

      List<Class<?>> classes = new ArrayList<Class<?>>();
      for (File file : classFiles) {
        if (!file.getName().endsWith("Test.class")) {
          continue;
        }
        String name = file.getPath().substring(classesDir.getPath().length() + 1)
          .replace('/', '.')
          .replace('\\', '.');
        name = name.substring(0, name.length() - 6);
        Class<?> c;
        try {
          c = Class.forName(name);
        }
        catch (ClassNotFoundException e) {
          throw new AssertionError(e);
        }
        if (!Modifier.isAbstract(c.getModifiers())) {
          classes.add(c);
        }
      }

      // sort so we have the same order as Ant
      Collections.sort(classes, new Comparator<Class<?>>() {
        public int compare(final Class<?> c1, final Class<?> c2) {
          return c1.getName().compareTo(c2.getName());
        }
      });

      return classes;
    }

    private static void findClasses(final List<File> classFiles, final File dir) {
      for (File file : dir.listFiles()) {
        if (file.isDirectory()) {
          findClasses(classFiles, file);
        }
        else if (file.getName().toLowerCase().endsWith(".class")) {
          classFiles.add(file);
        }
      }
    }
  }

  private static File findClassesDir() {
    try {
      String path = AllTests.class.getProtectionDomain()
        .getCodeSource().getLocation().getFile();
      return new File(URLDecoder.decode(path, "UTF-8"));
    }
    catch (UnsupportedEncodingException impossible) {
      // using default encoding, has to exist
      throw new AssertionError(impossible);
    }
  }
}

Incase anyone else is looking for a solution to this, I found an answer here on Burt Beckwith's website:

http://burtbeckwith.com/blog/?p=52

To use this, just right-click it in the class tree in Eclipse and click “Run As JUnit Test”.

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Modifier;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;
import org.junit.internal.runners.InitializationError;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Suite;

/**
 * Discovers all JUnit tests and runs them in a suite.
 */
@RunWith(AllTests.AllTestsRunner.class)
public final class AllTests {

  private static final File CLASSES_DIR = findClassesDir();

  private AllTests() {
    // static only
  }

  /**
   * Finds and runs tests.
   */
  public static class AllTestsRunner extends Suite {

    private final Logger _log = Logger.getLogger(getClass());

    /**
     * Constructor.
     *
     * @param clazz  the suite class - <code>AllTests</code>
     * @throws InitializationError  if there's a problem
     */
    public AllTestsRunner(final Class<?> clazz) throws InitializationError {
      super(clazz, findClasses());
    }

    /**
     * {@inheritDoc}
     * @see org.junit.runners.Suite#run(org.junit.runner.notification.RunNotifier)
     */
    @Override
    public void run(final RunNotifier notifier) {
      initializeBeforeTests();

      notifier.addListener(new RunListener() {
        @Override
        public void testStarted(final Description description) {
          if (_log.isTraceEnabled()) {
            _log.trace("Before test " + description.getDisplayName());
          }
        }

        @Override
        public void testFinished(final Description description) {
          if (_log.isTraceEnabled()) {
            _log.trace("After test " + description.getDisplayName());
          }
        }
      });

      super.run(notifier);
    }

    private static Class<?>[] findClasses() {
      List<File> classFiles = new ArrayList<File>();
      findClasses(classFiles, CLASSES_DIR);
      List<Class<?>> classes = convertToClasses(classFiles, CLASSES_DIR);
      return classes.toArray(new Class[classes.size()]);
    }

    private static void initializeBeforeTests() {
      // do one-time initialization here
    }

    private static List<Class<?>> convertToClasses(
        final List<File> classFiles, final File classesDir) {

      List<Class<?>> classes = new ArrayList<Class<?>>();
      for (File file : classFiles) {
        if (!file.getName().endsWith("Test.class")) {
          continue;
        }
        String name = file.getPath().substring(classesDir.getPath().length() + 1)
          .replace('/', '.')
          .replace('\\', '.');
        name = name.substring(0, name.length() - 6);
        Class<?> c;
        try {
          c = Class.forName(name);
        }
        catch (ClassNotFoundException e) {
          throw new AssertionError(e);
        }
        if (!Modifier.isAbstract(c.getModifiers())) {
          classes.add(c);
        }
      }

      // sort so we have the same order as Ant
      Collections.sort(classes, new Comparator<Class<?>>() {
        public int compare(final Class<?> c1, final Class<?> c2) {
          return c1.getName().compareTo(c2.getName());
        }
      });

      return classes;
    }

    private static void findClasses(final List<File> classFiles, final File dir) {
      for (File file : dir.listFiles()) {
        if (file.isDirectory()) {
          findClasses(classFiles, file);
        }
        else if (file.getName().toLowerCase().endsWith(".class")) {
          classFiles.add(file);
        }
      }
    }
  }

  private static File findClassesDir() {
    try {
      String path = AllTests.class.getProtectionDomain()
        .getCodeSource().getLocation().getFile();
      return new File(URLDecoder.decode(path, "UTF-8"));
    }
    catch (UnsupportedEncodingException impossible) {
      // using default encoding, has to exist
      throw new AssertionError(impossible);
    }
  }
}
灼疼热情 2024-09-25 21:54:59

我发现 Burt Beckwith 的代码很棒,但无论您将 AllTests 放在哪里,它都会运行项目中的每个测试。对一个函数的这一修改将允许您将 AllTests 放置在项目的任何子目录中,并且它只会在该位置下运行测试。

private static Class<?>[] findClasses() {List<File> classFiles = new ArrayList<File>();
  String packagepath = AllTests.class.getPackage().getName().replace(".", "/");
  File RELATIVE_DIR = new File( CLASSES_DIR.getAbsolutePath() + "\\" + packagepath );
  findClasses(classFiles, RELATIVE_DIR);
  List<Class<?>> classes = convertToClasses(classFiles, CLASSES_DIR);
  return classes.toArray(new Class[classes.size()]);
}

I found that Burt Beckwith's code is great but it will run every test in the project regardless of where you place AllTests. This modification to one function will allow you to place AllTests in any subdirectory of your project and it will only run tests under that location.

private static Class<?>[] findClasses() {List<File> classFiles = new ArrayList<File>();
  String packagepath = AllTests.class.getPackage().getName().replace(".", "/");
  File RELATIVE_DIR = new File( CLASSES_DIR.getAbsolutePath() + "\\" + packagepath );
  findClasses(classFiles, RELATIVE_DIR);
  List<Class<?>> classes = convertToClasses(classFiles, CLASSES_DIR);
  return classes.toArray(new Class[classes.size()]);
}
苹果你个爱泡泡 2024-09-25 21:54:59

您是否将 /test 添加到构建路径 ->源文件夹?

Did you add /test to Build Path -> Source Folders?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文