Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在JUnit4中创建一种抽象的超级测试类?_Java_Unit Testing_Junit - Fatal编程技术网

Java 如何在JUnit4中创建一种抽象的超级测试类?

Java 如何在JUnit4中创建一种抽象的超级测试类?,java,unit-testing,junit,Java,Unit Testing,Junit,考虑以下具体场景:有人创建了许多测试,完全测试实现集合的类必须遵守的功能。那么,如何使用该测试类(以某种方式)来测试集合的具体实现呢 举例来说: public class CollectionTest { //lots of tests here } public class ACollection<E> implements Collection<E> { //implementation and custom methods } public cl

考虑以下具体场景:有人创建了许多测试,完全测试实现
集合的类必须遵守的功能。那么,如何使用该测试类(以某种方式)来测试
集合的具体实现呢

举例来说:

public class CollectionTest {
    //lots of tests here
}

public class ACollection<E> implements Collection<E> {
    //implementation and custom methods
}

public class BCollection<E> implements Collection<E> {
    //implementation and other custom methods
}
公共类集合测试{
//这里有很多测试
}
公共类ACollection实现收集{
//实现和自定义方法
}
公共类BCollection实现收集{
//实现和其他自定义方法
}
然后,我应该如何编写测试类,以使代码重复最少

public class ACollectionTest {
    //tests for Collection<E>, preferably not duplicated
    //tests for custom methods
}

public class BCollectionTest {
    //tests for Collection<E>, preferably not duplicated
    //tests for other custom methods
}
公共类ACollectionTest{
//收集测试,最好不要重复
//自定义方法的测试
}
公共类B集合测试{
//收集测试,最好不要重复
//其他自定义方法的测试
}
换句话说,是否可以“扩展CollectionTest”,但可以在
ACollectionTest
BCollectionTest
(或更多)的实例上运行其测试?请注意,在使用
ACollection
作为
Collection
时,这些方法仍然可以访问。例如,在基类中:

protected Collection<Foo> collectionUnderTest;

@Test
public void shouldDoThis() {
    // uses collectionUnderTest
}

@Test
public void shouldDoThat() {
    // uses collectionUnderTest
}
protectedcollectionundertest;
@试验
公共空间应该做这件事{
//使用collectionUnderTest
}
@试验
公共空间应该是{
//使用collectionUnderTest
}
在子类中,特定于ACollection实现:

@Before
public void prepare() {
    this.collectionUnderTest = new ACollection<>();
}
@之前
公众假期准备(){
this.collectionUnderTest=新的集合();
}

我刚才看到了这个问题,这是否意味着自定义规则等不能再使用了?我不明白为什么不能使用它们。但这太模糊了。我的建议是:停止猜测或预测会发生什么,你能做什么,不能做什么。试着这样做,你会看到发生了什么。在这样的例子中可以应用
模拟吗?@LeonidDashko模拟在这里没有用,因为关键是要实际调用实现上的实际方法在guava中,存在一个InmutableSet(例如)的基础抽象测试,其中有一组方法来获取集合,请参阅和实现以及。