如何在地图中使用任何string()进行嘲笑验证? 我使用Mockito和Junit 5在Spring Boot应用程序中编写单元测试,我正在尝试验证一个方法调用,其中其中一个参数为map

问题描述 投票:0回答:1
public void someMethod(SomeClass obj, String parameter1, Map<String, String> properties) { ... }

我需要验证该方法是用包含某些键(property2和propert3)但任何字符串值的地图调用的。

这里是我的测试代码:

@Test void testMethodVerification() { Map<String, String> properties = Map.of( "property1", "TEST_VALUE", "property2", anyString(), // This causes an error "property3", anyString() // This causes an error ); verify(mockedService, times(1)).someMethod( any(SomeClass.class), eq("some_attribute"), eq(properties) // Issue occurs here ); }
,但是,我遇到了这个错误:

org.mockito.exceptions.misusing.UnfinishedVerificationException: Missing method call for verify(mock) here: -> at com.mycompany.myproject.MyTestClass.testMethodVerification(MyTestClass.java:XX)

问题: 我如何用“属性2”和“ property3”的地图验证是否被称为“属性”?
感谢任何指导!

i我尝试使用map.of()内部使用任何string()以允许灵活性验证属性2和属性3。但是,我遇到了一个不完整的verificationException,因为任何string()是一个参数匹配器,不能直接在map.of()中使用。
I期望Mockito验证该方法是否用包含“ property1”为固定值的地图和“属性2”和“ property3”作为任何字符串值。但是,由于不正确的匹配器使用情况,该测试失败了。

现在,我正在寻找正确的方法来验证一个方法调用,其中某些映射值可以是任何字符串,而其他键必须匹配特定值。

anyString()

仅当您在

when

verify

呼叫中使用它时才有效。如果您在外面使用它,它将只返回
java spring-boot mockito junit5
1个回答
0
投票
(并且损坏的Mockito的内部匹配器堆栈)。

如果您需要执行自定义匹配,

argThat
或自定义
ArgumentMatcher
实施工作:
    Map<String, String> properties = Map.of(
        "property1", "TEST_VALUE",
        "property2", anyString(), // This causes an error
        "property3", anyString() // This causes an error
    );

    verify(mockedService).someMethod(
        any(SomeClass.class),
        eq("some_attribute"),
        argThat(arg -> Objects.equals(arg.get("property1", "TEST_VALUE"))
            && arg.containsKey("property2")
            && arg.containsKey("property3")));
自定义实施使您可以覆盖其

toString

方法,如果您的验证失败并且您想知道实际值是什么,这非常有用。

	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.