简体   繁体   中英

How to test the abstract class methods?

How do I test the abstract class? I researched it and found I need to create a mock object, but how do I create a mock object? I have no idea, can somebody help please? For example this is my abstract class:

public abstract class Aging {
    private int age;

    public Aging(int age) {
        setAge(age);
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

I tried to use this code to test the constructor:

@Test
public void testAgingConstructor() {
    Aging a = new Aging(18);
    a.setAge(19);
    Aging b = new Aging(19);
    assertEquals(b, a);
}

and I got a error message "Aging is abstract; cannot be instantiated" . What should I do?

In order to instantiate your abstract class, you need to create a concrete subclass.

@Test
public void testAgingConstructor() {
    class AgingSubclass extends Aging {
        public AgingSubclass(int age) { super(age); }
    }
    Aging a = new AgingSubclass(18);
    a.setAge(19);
    Aging b = new AgingSubclass(19);
    assertEquals(b, a);
}

I would create a new non abstract class that extends your abstract class.it would be am empty class except the header with the extends clause. Then you wil will be able to test your methods implemented at the abstract class.

The question to ask yourself is :

Why do I need to test this class ?

Is it a class dedicated to be extended by some other modules ? then yes, you should test it by actually testing this usecase : extend your abstract class and verify the behavior you get is the intended one.

Is it a class that will be used in your module where you have some implementations ? Then you should most probably test the behaviour of those implementations and thus test the concrete classes.

All in all, what you'll end up testing is some concrete class that extend your abstract class.

Mocking allows you to do not care about the dependency of a class when testing it and has nothing to do with your problem.

And a nice trick you can use if you don't want to bother writing a concrete class is to leverage the use of anonymous classes :

@Test
public void testAgingConstructor() {
    Aging a = new Aging(18){}; //Create anonymous subclass and instantiate it. 
    a.setAge(19);
    Aging b = new Aging(19){};
    assertEquals(b, a);
}

For your class it should be as follows. It shows how to implement abstract classes inline (curly brackets). If you have abstract methods in your abstract class, you have to override and implement them inside curly brackets.

@Test
public void testAgingConstructor(){
    Aging a =new Aging(18) {};
    a.setAge(19);
    Aging b =new Aging(19) {};
    assertEquals(b,a);
}

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