简体   繁体   English

如何确定代码是否在 JUnit 测试中运行?

[英]How can I find out if code is running inside a JUnit test or not?

In my code I need to do certain fixes only when it is run inside a JUnit test.在我的代码中,只有在 JUnit 测试中运行时,我才需要进行某些修复。 How can I find out if code is running inside a JUnit test or not?如何确定代码是否在 JUnit 测试中运行? Is there something like JUnit.isRunning() == true ?有没有类似 JUnit.isRunning() == true 的东西?

It might be a good idea if you want to programmatically decide which "profile" to run.如果您想以编程方式决定运行哪个“配置文件”,这可能是个好主意。 Think of Spring Profiles for configuration.考虑使用 Spring Profiles 进行配置。 Inside an integration tests you might want to test against a different database.在集成测试中,您可能希望针对不同的数据库进行测试。

Here is the tested code that works这是经过测试的有效代码

public static boolean isJUnitTest() {  
  for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
    if (element.getClassName().startsWith("org.junit.")) {
      return true;
    }           
  }
  return false;
}


    

First of all, this a probably not a good idea.首先,这可能不是一个好主意。 You should be unit testing the actual production code, not slightly different code.您应该对实际的生产代码进行单元测试,而不是稍微不同的代码。

If you really want to do this, you could look at the stacktrace, but since you are changing your program for this anyway, you might just as well introduce a new static boolean field isUnitTesting in your code, and have JUnit set this to true.如果您真的想这样做,您可以查看isUnitTesting ,但由于您正在为此更改程序,您不妨在代码中引入一个新的静态布尔字段isUnitTesting ,并让 JUnit 将其设置为 true。 Keep it simple.把事情简单化。

Lots of people on this thread say that it's a bad idea for code to run slightly differently while under JUnit.该线程上的很多人都说,在 JUnit 下运行稍微不同的代码是一个坏主意。 I generally agree, but I think there are some exceptions.我大体上同意,但我认为也有一些例外。

For example, I am currently writing INTEGRATION (as opposed to Unit) tests for an app that connects to a DB.例如,我目前正在为连接到数据库的应用程序编写集成(而不是单元)测试。

These acceptance tests often need to completely reinitialize the DB with specific test data.这些验收测试通常需要使用特定的测试数据完全重新初始化数据库。

Obviously, I don't want this EVER, EVER to be done on an actual production DB, because that might completely erase valuable production data.显然,我不希望在实际生产数据库上执行此操作,因为这可能会完全删除有价值的生产数据。

The easiest way to guarantee that this will never happen, is to make it impossible for the code to connect to a production DB when it is running under JUnit.保证这种情况永远不会发生的最简单方法是,在 JUnit 下运行时,使代码无法连接到生产数据库。 This in turn can be done if, for example, the Factory that generates a connection can tell that it's running under JUnit, and in that case, will return a null connection unless the database we are trying to connect to has a name that is known to be a test database (ex: "testdatabase").例如,如果生成连接的工厂可以告诉它在 JUnit 下运行,那么这反过来可以完成,在这种情况下,除非我们尝试连接的数据库具有已知名称,否则将返回空连接成为测试数据库(例如:“testdatabase”)。

In my code I need to do certain fixes only when it is run inside a JUnit test.在我的代码中,仅当它在JUnit测试中运行时,才需要进行某些修复。 How can I find out if code is running inside a JUnit test or not?如何确定代码是否在JUnit测试内运行? Is there something like JUnit.isRunning() == true ?是否有类似JUnit.isRunning()== true的东西?

If you're doing things differently because you're doing a unit test you're defeating the purpose of a unit test.如果您因为进行单元测试而以不同的方式做事,那么您就违背了单元测试的目的。 A unit test is supposed to perform exactly like production would (except for the setup and teardown of any necessary data and such you need....but that is included in the JUnit test itself and not your code).单元测试应该像生产一样执行(除了任何必要数据的设置和拆卸以及您需要的数据......但这包含在 JUnit 测试本身而不是您的代码中)。

However, if you truly do have a good reason for this I'd look at the stack and see if JUnit is there.但是,如果您确实有充分的理由这样做,我会查看堆栈并查看 JUnit 是否存在。

如何检查 junit jar 是否在类路径中?

This has worked for me:这对我有用:

private Boolean isRunningTest = null;

private boolean isRunningTest() {
    if (isRunningTest == null) {
        isRunningTest = true;
        try {
            Class.forName("org.junit.Test");
        } catch (ClassNotFoundException e) {
            isRunningTest = false;
        }
    }
    return isRunningTest;
}

It can be used in Maven tests, as well as inside the Eclipse IDE, as long as junit is included as a dependency with scope "test", eg:它可以在 Maven 测试中使用,也可以在 Eclipse IDE 中使用,只要 junit 作为范围“test”的依赖项包含在内,例如:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>${junit.version}</version>
    <scope>test</scope>
</dependency>

When using Spring one can define a bean which holds this value.使用 Spring 时,可以定义一个保存此值的 bean。

In application context:在应用程序上下文中:

@Bean
public boolean isRunningTests() {
    return false;
}

In test application context:在测试应用程序上下文中:

@Bean
public boolean isRunningTests() {
    return true;
}

Inject the value to a Spring component:将值注入 Spring 组件:

@Resource
private boolean isRunningTests;

private void someMethod() {
    if (isRunningTests()) {
        ....

为了区分测试和无测试,您始终可以在 application-test.properties 中定义特殊属性或值。

The shortest (least code) solution is to have a global flag that is set when tests are not running.最短(最少代码)的解决方案是在测试运行时设置一个全局标志。 You can then set it once in your main() (or similar entry point) instead of setting it repeatedly in setup methods of all test classes.然后,您可以在main() (或类似的入口点)中设置一次,而不是在所有测试类的设置方法中重复设置它。 This will work as long as there is no other way to enter the code (no alternate main ).只要没有其他方法可以输入代码(没有备用main ),这就会起作用。

The second shortest solution is to scan the call stack for junit package like in Janning's answer .第二个最短的解决方案是像Janning's answer一样扫描 junit 包的调用堆栈。 This will work as far as junit doesn't hide itself behind another library and an executor.只要 junit 不会将自己隐藏在另一个库和执行程序后面,这就会起作用。

Dependency injection will work too, but in this case it's just a fancy way to set what's essentially a global flag.依赖注入也可以工作,但在这种情况下,它只是一种设置本质上全局标志的奇特方式。

this is not strictly related to the user question, but I'm pretty sure that someone that get there may find it useful.这与用户问题并不严格相关,但我很确定到达那里的人可能会发现它很有用。

I use the following approach: expose a package-local constructor that will be used from tests.我使用以下方法:公开一个将在测试中使用的包本地构造函数。

eg例如

src/main/java/ApplicationService.java src/main/java/ApplicationService.java

public class ApplicationService {
  private final Integer someInternalObject;

  public ApplicationService(String somePublicArgument) throws NumberFormatException {
    someInternalObject = Integer.valueOf(somePublicArgument, 16);
  }

  ApplicationService(Integer someInternalObject) {
     this.someInternalObject = someInternalObject;
  }
}

src/test/ApplicationServiceTest.Java src/test/ApplicationServiceTest.Java

public class ApplicationServiceTest {
  @Test
  public void testSomething() throws Exception {
    ApplicationService applicationService = new ApplicationService(0);
  }
}

expose it to all tests将其暴露给所有测试

not final classes不是期末班

Extend it in the tests and provide a public constructor for the package-local or protected one.在测试中扩展它并为包本地或受保护的包提供一个公共构造函数。

final classes期末班

Make a public Factory Method in the same package ( within tests ) that will create it using the package-local constructor.在将使用包本地构造函数创建它的同一个包(在测试中)中创建一个公共工厂方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM