简体   繁体   中英

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? 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?

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:

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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