所以我有一个 Android CookieManager 的包装类,并且我正在使用
Mockito-4.3.1
和 Mockito-inline-3.10.0
为其编写单元测试。如何存根类返回的单例?这是我尝试过的:
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
@Mock
CookieManager mCookieManager;
MockedStatic<CookieManager> cookieManagerMockedStatic;
// has getCookie() method that further calls CookieManager.getInstance().getCookie("cookieName").
CookieManagerWrapper cookieManagerWrapper;
@Before
public void setUp() {
cookieManagerMockedStatic = mockStatic(CookieManager.class);
when(CookieManager.getInstance()).thenReturn(mCookieManager);
cookieManagerWrapper = new CookieManagerWrapper();
}
@After
public void tearDown() {
cookieManagerMockedStatic.close();
}
@Test
public void myTest() {
when(mCookieManager.getCookie(anyString())).thenReturn("expectedValue");
final String resultCookie = cookieManagerWrapper.getCookie("cookieName");
assertEquals(resultCookie, "expectedValue");
}
}
但我得到的是:
Expected: "expectedValue"
but: was null
java.lang.AssertionError:
Expected: "expectedValue"
but: was null
存根的正确方法是什么?
你应该这样写存根:
cookieManagerMockedStatic.when(CookieManager::getInstance).thenReturn(mCookieManager);