将命令行参数传递给以编程方式运行的JUnit测试用例 [英] Pass command line arguments to JUnit test case being run programmatically

查看:166
本文介绍了将命令行参数传递给以编程方式运行的JUnit测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Java类运行JUnit测试:

I am attempting to run a JUnit Test from a Java Class with:

    JUnitCore core = new JUnitCore();
    core.addListener(new RunListener());
    core.run(classToRun);

问题是我的JUnit测试需要一个当前在JUnit测试中硬编码的数据库连接。

Problem is my JUnit test requires a database connection that is currently hardcoded in the JUnit test itself.

我正在寻找的是一种以编程方式运行JUnit测试的方法(上面),但是将我在我的Java类中创建的数据库连接传递给它,运行测试,在JUnit类中没有硬编码。

What I am looking for is a way to run the JUnit test programmatically(above) but pass a database connection to it that I create in my Java Class that runs the test, and not hardcoded within the JUnit class.

基本上类似于

    JUnitCore core = new JUnitCore();
    core.addListener(new RunListener());
    core.addParameters(java.sql.Connection);
    core.run(classToRun);

然后在classToRun中:

Then within the classToRun:

@Test
Public void Test1(Connection dbConnection){
    Statement st = dbConnection.createStatement();
    ResultSet rs = st.executeQuery("select total from dual");
    rs.next();
    String myTotal = rs.getString("TOTAL");
    //btw my tests are selenium testcases:)
    selenium.isTextPresent(myTotal);
}

我知道@Parameters,但它似乎不适用于此更多的是使用不同的值多次运行相同的测试用例。我希望我的所有测试用例共享一个数据库连接,我通过配置文件传递给我的java客户端,然后运行那些测试用例(也通过配置文件传入)。

I know about The @Parameters, but it doesn't seem applicable here as it is more for running the same test case multiple times with differing values. I want all of my test cases to share a database connection that I pass in through a configuration file to my java client that then runs those test cases (also passed in through the configuration file).

这可能吗?

PS我理解这似乎是一种奇怪的做事方式。

P.S. I understand this seems like an odd way of doing things.

推荐答案

您可以使用java系统属性来实现此目的。

You can use java system properties to achieve this.

只需在junit命令行中使用 -Dconnectionstring = foobar 传递所需内容,或使用java api获取系统属性使用 System.setProperty(String name,String value) System.getProperty(String name)以编程方式设置。

Simply pass what you need with -Dconnectionstring=foobar in the junit command line, or use the java api for system properties to set this programmatically, with System.setProperty(String name, String value), and System.getProperty(String name).

在测试中,您可以使用 @Before @BeforeClass 基于此属性设置公共对象,等待是否要为每个测试运行一次安装(在这种情况下可以使用类成员)或每个套件运行一次(然后使用静态成员) 。

In your tests, you can use the @Before or @BeforeClass to set up common objects based on this property, pending on whether you want to run the setup once for each test (in which case you can use class members) or once for each suite (and then use static members).

您甚至可以使用所有测试用例扩展的抽象类来分解此行为。

You can even factorize this behavior by using an abstract class which all your test cases extends.

这篇关于将命令行参数传递给以编程方式运行的JUnit测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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