繁体   English   中英

Mockito:在特定的类范围内模拟不同的类方法

[英]Mockito: Mocking different classes method in a specific class scope

我想和Mockito一起嘲笑

MyServiceClass (这不是实际的代码,只是一个意图类似的伪造示例)

public String getClassObjects() {
    OtherClassObject otherclass = OtherClassObject.createOtherClassObject();
    String id = otherclass.getParentObject().getId();
    return id;
}

因此,从本质上讲,我想模拟“ .getId()”,但仅在此类“ MyServiceClass”的上下文中,如果我在不同的类中调用相同的“ getId()”方法,则希望能够模拟不同的返回值。

这将在对OtherClassObject的每个方法调用中返回“ 3”

new MockUp<MyServiceClass>() {
        @Mock
        public String getId(){
            return "3";
        }
    };

有没有一种方法可以在特定类的范围内隔离对类对象的方法调用?

Plain Mockito无法模拟静态调用,因此您在这里需要PowerMock 为了达到期望,您应该像这样从模拟对象返回不同的值

// from your example it's not clear the returned type from getParentObject method. 
// I'll call it ParentObj during this example. Replace with actual type.
ParentObj poOne = mock(ParentObj.class); 
when(poOne.getId()).thenReturn("3");

ParentObj poTwo = mock(ParentObj.class);
when(poTwo.getId()).thenReturn("10");

...

OtherClassObject otherClassObjectMock = mock(OtherClassObject.class);
// return all your stubbed instances in order
when(otherClassObjectMock.getParentObject()).thenReturn(poOne, poTwo); 

PowerMockito.mockStatic(OtherClassObject.class);
when(OtherClassObject.createOtherClassObject()).thenReturn(otherClassObjectMock);

因此,您可以根据需要自定义模拟,指定所需的返回值,或传播对实际(真实)方法的调用。 不要忘记在类级别使用注释@RunWith(PowerMockRunner.class)@PrepareForTest(OtherClassObject.class)来激活PowerMock的魔力。

另一种想法是摆脱getClassObjects方法内部的静态调用,并使用构造函数传递工厂,这样您就可以轻松对其进行模拟,仅对单个类设置模拟对象。

希望能帮助到你!

暂无
暂无

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

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