如何确定代码是否在 JUnit 测试中运行? [英] How can I find out if code is running inside a JUnit test or not?

查看:22
本文介绍了如何确定代码是否在 JUnit 测试中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,只有在 JUnit 测试中运行时,我才需要进行某些修复.如何确定代码是否在 JUnit 测试中运行?有没有类似 JUnit.isRunning() == true 的东西?

In my code I need to do certain fixes only when it is run inside a JUnit test. How can I find out if code is running inside a JUnit test or not? Is there something like JUnit.isRunning() == true ?

推荐答案

如果您想以编程方式决定使用哪个配置文件"可能是个好主意.跑步.考虑使用 Spring Profiles 进行配置.在集成测试中,您可能希望针对不同的数据库进行测试.

It might be a good idea if you want to programmatically decide which "profile" to run. Think of Spring Profiles for configuration. 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;
}


    

这篇关于如何确定代码是否在 JUnit 测试中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆