简体   繁体   English

来自抽象类的超类的模拟字段

[英]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? 我的问题很简单,我有一个测试MyEpicAbstractClassTest ,它将测试子类MyEpicAbstractClass ,那么如何从超类中模拟messageWriter呢?

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(). 因此,对于具体的子类(A),您应该监视A的对象,然后模拟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. 或尝试使用一些实用程序,例如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 布兰登

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

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