【问题标题】:How to init setup on a Parameterized class test?如何在参数化类测试中初始化设置?
【发布时间】:2016-06-16 13:58:59
【问题描述】:

我有 2 个实现相同接口的具体类。两者都有相同的测试,所以我想做 1 Parameterized class test。 类最初只需要配置一次(使用相同的设置),所以这是我的解决方法:

@RunWith(Parameterized.class)
public class MyInterfaceTest {

    private MyInterface i;
    private static boolean setupDone[] = new boolean[2]; //this is ugly

    public MyInterfaceTest(MyInterface i) {
        this.i = i;
        if(i instanceof ImplA && !setupDone[0]){
            setup();
            setupDone[0] = true;
        }else if(i instanceof ImplB && !setupDone[1]){
            setup();
            setupDone[1] = true;
        }
        //must add code here for more Impl -> ugly
    }


    @Parameterized.Parameters
    public static Collection<Object[]> getParameters()
    {
        return Arrays.asList(new Object[][] {
                { new ImplA() },
                { new ImplB() }
        });
    }

    //tets...

}

这很丑陋。有什么更好的解决方案?

【问题讨论】:

  • 对于您的 getParameters 方法,您是否需要返回一个 Object 集合?您可以简单地将数组类型更改为 &lt;MyInterface&gt; 以避免在构造函数中进行强制转换。
  • 我做的演员是确定哪个Impl是i
  • 是的,但是因为它们都继承了MyInterface 的方法,所以你可能不需要。如果您需要测试MyInterface 具有的方法,那么您可以调用MyInterface 对象的数组而无需强制转换。你只需要强制转换如果实现有其他唯一的方法名称,你也需要测试这些。
  • 没有。我的目标是设置每个 Impl 一次。如果我重新设置那是错误的。只能执行一次。
  • 抱歉,我可能只是误解了您对每个实现的设置是如何完成的。

标签: java integration-testing junit4


【解决方案1】:
@RunWith(Parameterized.class)
public class ServiceLocator1Test {

    private MyInterface i;

    public MyInterfaceTest(MyInterface i) {
        this.i = i;
    }


    @Parameterized.Parameters
    public static Collection<Object[]> getParameters()
    {
        MyInterface a = new ImplA(); setup(a);
        MyInterface b = new ImplB(); setup(b);

        return Arrays.asList(new Object[][] {
                { a },
                { b }
        });
    }

    //tets...

}

private static void setup(MyInterface myinterface){/*...*/}

【讨论】:

    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多