简体   繁体   English

模拟子类对象和超类引用

[英]Mocking subclass object and superclass reference

Here is the scenario, I have something like this in one of my method of cls: 这是场景,我在我的一个cls方法中有这样的东西:

public class xyz{
    public Object build(Map map) {

       BaseClass cls;

       if(SomeconditionTrue) {
         cls = new ChildClass1(new ABC());
       } else {
         cls = new ChildClass2(new ABC());
       }

       cls.callMethod();
    }
}

For the above scenario, I am writing a test case using PowerMockito, I want to mock this method call, cls.callMethod() . 对于上面的场景,我正在使用PowerMockito编写测试用例,我想模拟这个方法调用cls.callMethod() When i am trying the normal mocking, it calls the actual Method callMethod() that is failing. 当我尝试正常的callMethod() ,它调用失败的实际方法callMethod() can some body please help me to mock that method call? 有人可以帮我模仿那个方法吗? Tried using couple of scenarios using PowerMockito.stub and some of other options, but its always calling the actual method. 使用PowerMockito.stub和一些其他选项尝试使用几个场景,但它总是调用实际方法。

Using Powermock you could do something like the following: 使用Powermock,您可以执行以下操作:

PowerMockito.whenNew(ChildClass1.class)
        .withArguments(any(ABC.class))
        .thenReturn(mockedBaseClass);

    PowerMockito.whenNew(ChildClass2.class)
        .withArguments(any(ABC.class))
        .thenReturn(mockedBaseClass);

Of course my preferred approach would be to pass in a factory that knows about how to make these ChildClass instances, then you could mock it using Mockito and it would be cleaner. 当然我的首选方法是传入一个知道如何制作这些ChildClass实例的工厂,然后你可以使用Mockito来模拟它,它会更干净。 However if that is not an option, hopefully the above should work. 但是,如果这不是一种选择,希望上述情况应该有效。

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

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