Java jUnit:在任何测试类之前运行的测试套件代码 [英] Java jUnit: Test suite code to run before any test classes

查看:97
本文介绍了Java jUnit:在任何测试类之前运行的测试套件代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试套件类:

@RunWith(Suite.class)
@Suite.SuiteClasses({
    GameMasterTest.class,
    PlayerTest.class,
})
public class BananaTestSuite { 

在包含实际测试的任何类之前,我需要使用什么注释来使此类中的函数运行?现在,我正在这样做,它可以工作,但它不是那么可读:

What annotation do I need to use to make a function in this class run before any of the classes containing actual tests? Right now, I'm doing this, and it works, but it's not as readable as it could be:

static {
    try {
        submitPeelAction = new Player(new GameMaster(1)).getClass().getDeclaredMethod("submitPeelAction");
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    submitPeelAction.setAccessible(true);
}

我试过 @BeforeClass 但它没有用。

推荐答案

创建一个包含用@BeforeClass注释的方法的超级测试类。扩展此类中的所有测试类,例如,

Make a super test class containing the method annotated with @BeforeClass. Extend all the test classes from this class, eg,

@Ignore
public class BaseTest {
    @BeforeClass
    public static void setUpBaseClass() {
        //Do the necessary setup here
    }
}

此方法将在子类中的任何@BeforeClass注释方法之前运行:
确保未在任何子类中使用此方法名称以防止出现阴影。

This method will run before any @BeforeClass annotated method in the subclasses: Source. Ensure that this method name is not used in any subclass to prevent shadowing.

如果你只需要运行一次(例如,如果要为所有要使用的测试创建/初始化大型资源),请在超类中设置一个标志检查方法是否运行。

If you need to run this just once (eg, if you are creating/initializing a large resource for all tests to use), set a flag in the super class to check whether the method ran or not.

此设计还将确保如果您更改测试运行器,则无需更改其他任何内容。

This design will also ensure that if you change the test runner, you need not change anything else.

这篇关于Java jUnit:在任何测试类之前运行的测试套件代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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