简体   繁体   中英

Mocking field from super class from abstract class

I have an abstract class:

public abstract MySuperEpicAbstractClass {
    @Autowired
    private IMessageWriter messageWriter;

    protected IMessageWriter getMessageWriter() {
        return messageWriter;
    }
}

public abstract class MyEpicAbstractClass extends MySuperEpicAbstractClass {
    //This class usses the getMessageWriter();
}

My question is simple, I have a test MyEpicAbstractClassTest that will test the subclass MyEpicAbstractClass , so how do I mock the messageWriter from the super class?

It would be good, if you can add some part of your test code where you invoke tests.I think you can spy on a real object and then mock one of the method in it. So for a concrete sub class (A), you should spy the object of A and then mock getMessageWriter(). Something like this.Check out.

ConcreteSubClass subclass = new ConcreteSubClass();
subclass  = Mockito.spy(subclass );
Mockito.doReturn(msgWriterObj).when(subclass).getMessageWriter();

Or try for some utilities like ReflectionTestUtils.

While there are many ways of doing this, the "Low tech", "No Framework", and "No Refactoring" version would be to simply shunt it out in your test. It could look something like this:

public MyEpicAbstractClassTest {
    public void testThatNeedsTheFakeMessageWriter() {
        ShuntedMyEpicAbstractClass meac = new ShuntedMyEpicAbstractClass();

        meac.doSomething("Arguments");

        verify(meac.getMessageWriter()).write("Arguments");
    }
}

// And the shunt is here
public class ShuntedMyEpicAbstractClass extends MyEpicAbstractClass {
    private IMessageWriter stubbedWriter = Mockito.mock(IMessageWriter.class);

    public IMessageWriter getMessageWriter() {
       return stubbedWriter;
    }
}

This technique is often useful when you don't have the option of refactoring the base class as one other poster suggested.

Hope this helps!

Brandon

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