Mockito:使用@InjectMocks时,模拟一个被测试方法调用的同一个类的方法

时间:2018-06-04 15:19:30

标签: java mockito

我有一个我想测试的类,它有几个外部依赖项,还有几个内部方法。我想为MethodA编写一个测试,但是让方法A对MethodB进行内部调用以实际练习MethodB。我想模拟/存根MethodB并返回一些特定的东西。通常我会使用when/thenReturn,但它的行为并不像我预期的那样 - 它实际上是在创建模拟本身时跳转到方法B中。

MyService.java

@Service
public class MyService {

  @Autowired
  private ServiceA serviceA;

  @Autowired
  private ServiceB serviceB;

    public SomeObject methodA() {
      // some logic using serviceA.method and serviceB.method that creates "output"
      SomeObject someObject = methodB(output);
      return someObject;
    }

    public SomeObject methodB(SomeObject someObject) {
      // deep mysteries done here to someObject
      return someObject 
    }
}

MyServiceTest.java

public class MyServiceTest {

  @Mock
  private ServiceA serviceA;

  @Mock
  private ServiceB serviceB;

  @InjectMocks
  private MyService myService;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void methodATest() {
    when(serviceA.method()).thenReturn(stuff);
    when(serviceB.method()).thenReturn(otherStuff);

    // here is what I would like to do
    when(myService.methodB()).thenReturn(mockedSomeObject); //<- doesn't work

    assertThat(myService.methodA().getSomeObjectProperty())
        .isEqualTo("property");
  }
}

我已经查看了使用MyService手动模拟Mockito.mock(MyService.class)类的解决方案,但是(因为上面的示例显然是做作的)我的实际类有很多外部依赖项,我更喜欢一个解决方案仍然允许我使用@Mock@Autowired依赖项和@InitMocks模拟服务,除非它根本不可能。

我试过了:

Mockito.doReturn(mockedSomeObject).when(myService.methodB(any(SomeObject.class));

但是在为该方法创建模拟时也会进入MethodB,这不应该发生。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

尝试将@Spy添加到InjectMocks并使用该对象以稍微不同的语法“期望”它们。

import org.mockito.Spy;

 @InjectMocks
 @Spy
 private MyService myService; 

现在模拟服务电话

 Mockito.doReturn(mockedSomeObject).when(myService).methodB();

同时更改对此

的其他模拟调用
Mockito.doReturn(stuff).when(serviceA).method();
Mockito.doReturn(otherStuff).when(serviceB).method();

答案 1 :(得分:0)

您需要将对象标记为Spy,或使用MyClass objA=null; MyClass spy_objA=Powermockito.spy(objA) doReturn(what_you_want).when(spy_objA).method()

为其显式创建Spy对象

编辑:可以找到您可能想要检查的类似问题 How to mock another method in the same class which is being tested?

相关问题