使用 Mockito 内联模拟和存根返回 Singleton 的类

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

所以我有一个 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

存根的正确方法是什么?

java junit mockito
1个回答
0
投票

你应该这样写存根:

cookieManagerMockedStatic.when(CookieManager::getInstance).thenReturn(mCookieManager);
© www.soinside.com 2019 - 2024. All rights reserved.