简体   繁体   English

Java-如何测试抽象类的非抽象方法?

[英]Java - How to test the non-abstract methods of an abstract class?

I have an abstract class that features no abstract methods... How would one go about testing this? 我有一个没有任何抽象方法的abstract类...如何进行测试? Can I simply import it into a test class and go about business as usual? 我可以简单地将其导入测试班并照常营业吗?

Example: 例:

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";
    }

}

Say I pass in an arg for db.url of localhost:8080 , and I wanted to test that the doSomethingToUrl method did output the new string... Would it still be in this format? 假设我为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));
    }
}

You wouldn't be able to create an instance of just SomeAbstractClass , no - but you could create an anonymous subclass: 您将无法仅创建SomeAbstractClass的实例,而不能-但您可以创建一个匿名子类:

private SomeAbstractClass sac = new SomeAbstractClass() {};

You may well want to create a concrete subclass just for the sake of testing though - so that any time you do add abstract methods, you just need to put them there. 您可能只想为了测试而创建一个具体的子类-因此, 每次添加抽象方法时,都只需要将它们放在那里即可。

While I suspect you could use a mocking framework for this, I suspect it would add more complexity for little benefit, unless you need to check under what situations the abstract methods are called. 虽然我怀疑您可以为此使用模拟框架,但我怀疑它会增加更多的复杂性而几乎没有好处,除非您需要检查在什么情况下调用了抽象方法。 (Mocks are great for interaction testing, but can be brittle for other purposes.) It could easily make for more confusing error messages (due to the infrastructure involved) as well. (模拟对于交互测试非常有用,但是对于其他目的则是脆弱的。)由于涉及的基础架构,它很容易使错误信息更加混乱。

You cannot initialize an abstract class, so your test class wouldn't compile as is. 您无法初始化abstract类,因此您的测试类无法原样编译。

You can either use an anonymous instance (the example below should suffice): 您可以使用一个匿名实例(下面的示例就足够了):

SomeAbstractClass sac = new SomeAbstractClass(){};

However, I would actually recommend you mock the class by means of a mocking framework such as Mockito or EasyMock . 但是,我实际上建议您通过诸如MockitoEasyMock的 模拟框架来模拟类。

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

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