1

I've class method like below which creates a local object and calls a method on that local object.

public class MyClass {
    public someReturn myMethod(){
        MyOtherClass otherClassObject = new MyOtherClass();
        boolean retBool = otherClassObject.otherClassMethod();
        if(retBool){
            // do something
        }
    }
}

public class MyClassTest {
    @Test
    public testMyMethod(){
        MyClass myClassObj = new MyClass();
        myClassObj.myMethod();
        // please get me here.. 
    }
}

When I'm testing myMethod, I want to mock otherClassObject.otherClassMethod to return something of my choice. otherClassMethod does some class to Message Queues and I don't want that in Unit test. So I want to return true when I do otherClassObj.otherClassMethod(). I know I must have used a factory for MyOtherClass instantiation in this case but it's legacy code and I don't want to change any code now. I see that Mockito doesn't provide this facility to mock MyOtherClass in this case but possible with PowerMockito. However, I could not find an example for above scenario but found only for static class. How should I mock local object inside a method of SUT ?

I also referred to some other OS questions like - Mocking methods of local scope objects with Mockito but they were not helpful.

A code example will be of great help.

4

2 回答 2

4

如果您使用的是 PowerMockito,则可以使用该whenNew方法

它应该看起来像这样:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)  //tells powerMock we will modify MyClass to intercept calls to new somewhere inside it
public class MyClassTest{

    @Test
    public void test(){
          MyOtherClass myMock = createMock(MyOtherClass.class);
          //this will intercept calls to "new MyOtherClass()" in MyClass
          whenNew( MyOtherClass.class).withNoArguments().thenReturn( myMock) );
          ... rest of test goes here

   }

另外这个其他 SO 帖子也有示例代码PowerMockito Mocking whenNew 不生效

于 2015-04-01T18:46:22.573 回答
2

好的,这不是一个真正的答案,但使用 PowerMockito 你可以做到这一点:

final MyOtherClass myOtherClass = mock(MyOtherClass.class);
// mock the results of myOtherClass.otherClassMethod();

PowerMockito.whenNew(MyOtherClass.class).withNoArguments()
    .thenReturn(myOtherClass);

// continue with your mock here

现在,不确定你是否真的需要这个 otherClassMethod 的结果,但如果你不需要,我建议你模拟结果myMethod()- 除非myMethod()是你想要测试的,因为这个其他方法对它有影响,是的,在这种情况下,应该考虑重构......而不是延迟ad vitam aeternam......

于 2015-04-01T18:43:08.480 回答