简体   繁体   English

JUnit类别-如何避免代码重复

[英]JUnit Category - how to avoid code duplication

Let's say I have two test classes annotated with proper categories: 假设我有两个带有适当类别的测试类:

@Category({CategoryA.class})
public class A {
   ...
}

and

@Category({CategoryB.class})
public class B {
   ...
}

which share common codebase and differ only in 1 line of test method. 共享通用代码库,仅在1行测试方法上有所不同。 What would be the best approach to make this code better? 使该代码更好的最佳方法是什么? For example, if I use only one class: 例如,如果我只使用一个类:

@Category({CategoryA.class, CategoryB.class})
public class AB {
   ...
}

Is there any way to determine category in runtime and add simple if statement? 有什么方法可以在运行时确定类别并添加简单的if语句?

Any reason you can't have an abstract class which does most of the work, then two extending classes and have different @Category annotations? 有什么理由不能让您完成大部分工作的抽象类,然后再扩展两个类并使用不同的@Category注释? Something like: 就像是:

public abstract class ABParent {
    protected abstract void thingThatsDifferent();
}

@Category(CategoryA.class)
public class A extends ABParent {
    @Override
    protected void thingThatsDifferent() {
        System.out.println("Woof");
    }
}

@Category(CategoryB.class)
public class B extends ABParent {
    @Override
    protected void thingThatsDifferent() {
        System.out.println("Meow");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM