我想模拟一个类的构造函数,并且仍然使用 Mockito 调用该类的真实方法

问题描述 投票:0回答:1

我正在尝试对 A 类进行单元测试,我在其构造函数 getB() 中调用一个方法。我想对这个类 A 进行单元测试,而不在构造函数内调用此方法,以便测试类内的其他方法。

class A {
  B b;

  public A() {
    B = getB();
  }

  doSomething() {
    b.doOtherThing();
  }

  getB() {
    return somethingThatReturnB;
  }
}

@Test
class TestA {
  @Spy
  A a;

  @Mock
  B b;

  @BeforeMethod
  public void beforeMethod() {
    MockiyoAnnotations.openMocks(this);
  }

  @Test
  public void testMethod() {
    doReturn(smt).when(b).doOtherThing();
    a.doSomething();
  }
}

我尝试了模拟构造函数,但这并没有调用我想要测试的真正方法。

java mockito testng
1个回答
0
投票

Mockito 有一个

when(systemUnderTest.methodToTest()).thenCallRealMethod();
选项,允许您显式调用真正的方法。不过,您必须为类中的每个方法执行此操作

© www.soinside.com 2019 - 2024. All rights reserved.