我有一个jUnit测试来测试我的一个函数。在该函数中,我调用另一个类的方法,我想使用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。
答案 0 :(得分:3)
Mockito将允许您创建模拟对象并使其方法返回预期结果。因此,在这种情况下,如果您希望模拟的AuthHelper实例的authenticateUser方法返回true,而不管HashMap参数的值如何,您的代码将如下所示:
AuthHelper mockAuthHelper = mock(AuthHelper.class);
when(mockAuthHelper.authenticateUser(any(HashMap.class))).thenReturn(true);
但是,您的模拟对象对您的MainClassImTesting没用,除非它有访问权或引用它。您可以通过将AuthHelper添加到MainClassImTesting的构造函数来实现这一点,以便类(包括您的测试方法)可以访问它。
MainClassImTesting unitUnderTest = new MainClassImTesting(mockAuthHelper);
Boolean response = unitUnderTest.test();
assertTrue(response);
或者,如果您的测试方法是唯一需要AuthHelper的方法,您可以简单地将AuthHelper设为方法参数。
MainClassImTesting unitUnderTest = new MainClassImTesting();
Boolean response = unitUnderTest.test(mockAuthHelper);
assertTrue(response);
答案 1 :(得分:0)
如果要模拟任何类型A参数的函数调用,只需执行:
AuthHelper authHelper = Mockito.mock(AuthHelper.class);
Mockito.when(authHelper.authenticateUser(any(A.class))).thenReturn(true);