如何使用构造函数注入模拟类

ir2*_*pid 5 java testing android unit-testing mockito

如何在Mockito中获得构造函数注入

我有以下课程:

class A{

  private B mB;

  A(B b){
     mB = b;
  }

 void String someMethod(){
     mB.execute();
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何someMethod使用模拟类A和类B进行测试

B b = Mockito.mock(B.class)
Mockito.when(b.execute().thenReturn("String")

A a = Mockito.mock(A.class)
//somehow inject b into A and make the below statement run
Mockito.when(a.someMethod()).check(equals("String"))
Run Code Online (Sandbox Code Playgroud)

ras*_*man 6

你想someMethod()考试A。测试execute()of 类B应该在其他测试中进行,因为 of 的实例B在您的情况下是依赖项。测试execute()应在不同的测试中进行。

您不需要测试 B 对象的行为方式,因此您需要模拟它,然后检查它是否execute()被调用。

因此,在您的情况下,您的测试将如下所示:

  B b = Mockito.mock(B.class);
  A a = new A( b );
  a.someMethod();
  Mockito.verify( b, Mockito.times( 1 ) ).execute();
Run Code Online (Sandbox Code Playgroud)


Hat*_*ice 6

您需要创建真正的 A 类,因为您想测试它,但您需要模拟 A 类中使用的其他类。此外,您可以找到 mockito文档说不要嘲笑一切。

class ATest {
        @Mock
        private B b;
        private A a;
        @Before
        public void init() {
            MockitoAnnotations.initMocks(this);
            a = new A(b);
        }
        @Test
        public String someMethodTest() {
            String result = "result";
            Mockito.when(b.execute()).thenReturn(result);
            String response = a.someMethod();
            Mockito.verify(b,  Mockito.atLeastOnce()).execute();
            assertEquals(response, result);
        }
    }
Run Code Online (Sandbox Code Playgroud)


sta*_*032 5

将模拟注入真实对象(因为 A 应该是真实对象)的另一种方法是使用注释,它们将创建您想要的对象:

@Mock 
B mockOfB;

@InjectMocks
A realObjectA;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}
Run Code Online (Sandbox Code Playgroud)

然后,就像他们说的那样,在没有 mockito 的情况下运行你想测试的方法(因为你想测试它,所以在真实实例上调用它)并根据你的期望检查结果。

可以以任何方式模拟对象 B 的行为,以满足您的需求。