gpt4 book ai didi

java - 使用 Mockito,如何在 when 子句中检查映射的键值对

转载 作者:行者123 更新时间:2023-12-02 01:41:56 24 4
gpt4 key购买 nike

引用:SimilarQuestion1 , SimilarQuestion2 , SimilarQuestion3

从引用文献中,我能够得出如下的部分解决方案,尽管它在语法上是不正确的。如何修改它以正确搜索具有空值的某些键。

when(storedProc.execute(anyMapOf(String.class, Object.class).allOf(hasEntry("firstIdentifier", null), hasEntry("secondIdentifier", null))))
.thenThrow(new Exception(EXCEPTION_NO_IDENTIFIER));

任何帮助将不胜感激。

最佳答案

在您的情况下,您可以将 eq 与提供的填充 map 一起使用:

    when(storedProc.execute(Mockito.eq(givenIncorrectMap)))
.thenThrow(new Exception(EXCEPTION_NO_IDENTIFIER));

完整示例:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;

import static org.mockito.Mockito.when;

public class QuestionTest {
@Rule
public ExpectedException exception = ExpectedException.none();

interface A {
String execute(Map<String, Object> map);
}

@Test
public void test() {
// Given a map with missed identifiers.
final Map<String, Object> givenIncorrectMap = new HashMap<>();
givenIncorrectMap.put("firstIdentifier", null);
givenIncorrectMap.put("secondIdentifier", null);

// Given a mocked service
final A mockedA = Mockito.mock(A.class);

// which throws an exception exactly for the given map.
when(mockedA.execute(Mockito.eq(givenIncorrectMap)))
.thenThrow(new IllegalArgumentException("1"));


// Now 2 test cases to compare behaviour:


// When execute with correct map no exception is expected
mockedA.execute(Collections.singletonMap("firstIdentifier", "any correct value"));

// When execute with incorrect map the IllegalArgumentException is expected
exception.expect(IllegalArgumentException.class);
exception.expectMessage("1");

mockedA.execute(givenIncorrectMap);
}
}

关于java - 使用 Mockito,如何在 when 子句中检查映射的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54352352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com