简体   繁体   English

使用 Mockito 在迭代器中模拟静态方法调用

[英]Mocking a static method call inside iterator using Mockito

I am totally new to this.我对此完全陌生。 Pardon me for my primitive knowledge about the same.请原谅我对这方面的原始知识。 So, this is the piece of code I am testing所以,这是我正在测试的一段代码

private static void updateRules(String id) throws IOException {
    // Make list
    List<String> select = Arrays.asList(
            ID,
            NAME,
            APP_RULES,
            RULE_CONFIG);
    // Fetch list
    List<Map<String, Object>> entries = StaticUtil.list(select, id);
    // Iterate over the entries
    for (Map<String, Object> obj : entries) {
        // Call create
        CreateStaticUtils.create();
    }
}

I am trying to mock this function's behavior,我试图模拟这个函数的行为,

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticUtil.class)
class MyTest {    
    private Iterator<String> listIterator;
    
    @SuppressWarnings("unchecked")
    @Test
    public final void testUpdateRules() throws IOException {
        PowerMockito.mockStatic(StaticUtil.class);
        PowerMockito
        .when(StaticUtil.list(Mockito.anyListOf(String.class),
                Mockito.anyString()))
        .thenReturn(Mockito.anyList());
        PowerMockito.verifyStatic(Mockito.times(1));
        
        listIterator = mock(Iterator.class);
        when(listIterator.hasNext()).thenReturn(<**Confused here**>)
    }

Am I not sure how to validate CreateStaticUtils.create() call inside the iterator .我不确定如何验证CreateStaticUtils.create() call inside the iterator

How to mock and validate the same interaction inside?如何在内部模拟和验证相同的交互?

Also, do I have to put that also as @PrepareForTest(CreateStaticUtils.class) ?另外,我是否必须把它也作为@PrepareForTest(CreateStaticUtils.class)

Please help me with the same?请帮我一样吗?

Do you really have to mock it?你真的有必要嘲笑它吗? If the static method (class) implementation is not in external API, you can surely create an instance of tested class in this test or any factory for creating this instance, and just testing it like normal functionality, without mocks如果静态方法(类)实现不在外部 API 中,您肯定可以在此测试或任何用于创建此实例的工厂中创建测试类的实例,并像正常功能一样对其进行测试,无需模拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM