如何在 java junit 测试中使用 mockito 模拟对函数的调用
How can I mock a call to a function using mockito in a java junit test
我有一个 jUnit 测试来测试我的一个函数。在该函数中,我调用了另一个 class 的方法,我想使用 mockito 模拟该方法。但是,我似乎无法真正嘲笑这一点。这是我的 jUnit 测试的样子:
@Test
public void testingSomething() throws Exception {
mock(AuthHelper.class);
when(new AuthHelper().authenticateUser(null)).thenReturn(true);
Boolean response = new MainClassImTesting().test();
assertTrue(response);
}
编辑:在我正在调用的 MainClassImTesting().test() 函数中,它调用 authenticateUser() 并向其传递一个 hashMap。
如果您想模拟 A 类型的任何参数的函数调用,只需执行:
AuthHelper authHelper = Mockito.mock(AuthHelper.class);
Mockito.when(authHelper.authenticateUser(any(A.class))).thenReturn(true);
Mockito 将允许您创建模拟对象并使其方法具有 return 预期结果。因此,在这种情况下,如果您希望模拟的 AuthHelper 实例的 authenticateUser 方法 return 为真,而不管 HashMap 参数的值如何,您的代码将如下所示:
AuthHelper mockAuthHelper = mock(AuthHelper.class);
when(mockAuthHelper.authenticateUser(any(HashMap.class))).thenReturn(true);
但是,您的模拟对象对您的 MainClassImTesting 毫无用处,除非它可以访问或引用它。您可以通过将 AuthHelper 添加到 MainClassImTesting 的构造函数来实现这一点,以便 class(包括您的测试方法)可以访问它。
MainClassImTesting unitUnderTest = new MainClassImTesting(mockAuthHelper);
Boolean response = unitUnderTest.test();
assertTrue(response);
或者如果您的测试方法是唯一需要 AuthHelper 的方法,您可以简单地将 AuthHelper 设为方法参数。
MainClassImTesting unitUnderTest = new MainClassImTesting();
Boolean response = unitUnderTest.test(mockAuthHelper);
assertTrue(response);
我有一个 jUnit 测试来测试我的一个函数。在该函数中,我调用了另一个 class 的方法,我想使用 mockito 模拟该方法。但是,我似乎无法真正嘲笑这一点。这是我的 jUnit 测试的样子:
@Test
public void testingSomething() throws Exception {
mock(AuthHelper.class);
when(new AuthHelper().authenticateUser(null)).thenReturn(true);
Boolean response = new MainClassImTesting().test();
assertTrue(response);
}
编辑:在我正在调用的 MainClassImTesting().test() 函数中,它调用 authenticateUser() 并向其传递一个 hashMap。
如果您想模拟 A 类型的任何参数的函数调用,只需执行:
AuthHelper authHelper = Mockito.mock(AuthHelper.class);
Mockito.when(authHelper.authenticateUser(any(A.class))).thenReturn(true);
Mockito 将允许您创建模拟对象并使其方法具有 return 预期结果。因此,在这种情况下,如果您希望模拟的 AuthHelper 实例的 authenticateUser 方法 return 为真,而不管 HashMap 参数的值如何,您的代码将如下所示:
AuthHelper mockAuthHelper = mock(AuthHelper.class);
when(mockAuthHelper.authenticateUser(any(HashMap.class))).thenReturn(true);
但是,您的模拟对象对您的 MainClassImTesting 毫无用处,除非它可以访问或引用它。您可以通过将 AuthHelper 添加到 MainClassImTesting 的构造函数来实现这一点,以便 class(包括您的测试方法)可以访问它。
MainClassImTesting unitUnderTest = new MainClassImTesting(mockAuthHelper);
Boolean response = unitUnderTest.test();
assertTrue(response);
或者如果您的测试方法是唯一需要 AuthHelper 的方法,您可以简单地将 AuthHelper 设为方法参数。
MainClassImTesting unitUnderTest = new MainClassImTesting();
Boolean response = unitUnderTest.test(mockAuthHelper);
assertTrue(response);