我有一个abstract
类,它没有 抽象方法...如何测试它?我可以简单地将它导入测试类并照常进行吗?
例子:
public abstract class SomeAbstractClass implements SomeOtherClass {
// Some variables defined here
private static final String dbUrl = System.getProperty("db.url");
// Some public methods
public String doSomethingToUrl(String url) {
url = url + "/takeMeSomewhereNice";
}
}
假设我为 localhost:8080
的 db.url
传递了一个 arg,我想测试 doSomethingToUrl
方法是否输出新字符串...它仍然是这种格式吗?
public class TestUrl {
SomeAbstractClass sac = new SomeAbstractClass();
@Test
public void testUrlChange() throws Exception {
String testUrl = "localhost:8080";
assertThat("localhost:8080/takeMeSomewhereNice",
sac.doSomethingToUrl(testUrl));
}
}
最佳答案
你不能只创建一个 SomeAbstractClass
的实例,不 - 但你可以创建一个匿名子类:
private SomeAbstractClass sac = new SomeAbstractClass() {};
不过,您可能只是为了测试而想创建一个具体的子类 - 这样任何时候您确实添加了抽象方法,您只需要将它们放在那里。
虽然我怀疑您可以为此使用模拟框架,但我怀疑它会增加更多的复杂性而没有什么好处,除非您需要检查在什么情况下调用抽象方法。 (模拟非常适合交互测试,但对于其他用途可能很脆弱。)它也很容易产生更令人困惑的错误消息(由于涉及的基础设施)。
关于Java - 如何测试抽象类的非抽象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816951/