Mockito,当参数为函数时验证函数调用

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

您能否建议我如何通过 Mockito 检查函数调用是否参数也是函数。

我们假设三个服务类别,为简洁起见省略了详细信息

class SomeService {
 public void process(SomeType type1) {...}
 public void process(AnotherType type2) {...}
}

class AnotherService {
 public SomeType anotherProcess(args) {...}
}

class ServiceForTests {
 public void mainProcess() {
    someService.process(anotherService.anotherProcess(args))
 }
}

我需要检查 process 是否在 ServiceForTests.mainProcess 中调用。

代码 verify(someService).process(any(SomeType.class)) 由于参数差异而失败。想要:任何 SomeType,但实际:anotherService.anotherProcess

我无法使用 verify(someService).process(any()) 进行测试,因为 SomeService.process 已过载。

java mockito verify
1个回答
0
投票

请确认您是否正确执行了所有操作,或者我可能理解错误了您的问题。

我在本地复制了它,它似乎对我来说没问题。

复制代码

一些服务
public class SomeService {
    public void process(String T1) {}
    public void process(Map<String,String> T2) {}
}
另一项服务
public class AnotherService {
    public String anotherProcess() {
        return "Hello World";
    }
}
测试服务
public class ServiceForTests {
    public SomeService someService;
    public AnotherService anotherService;

    public ServiceForTests(SomeService someService, AnotherService anotherService) {
        this.someService = someService;
        this.anotherService = anotherService;
    }

    public void mainProcess() {
        someService.process(anotherService.anotherProcess());
    }
}
测试服务
@ExtendWith(MockitoExtension.class)
public class TestServiceForTests {

    ServiceForTests classUnderTest;

    @Mock
    private SomeService someService;
    @Mock
    private AnotherService anotherService;

    @BeforeEach
    public void setUp() {
        classUnderTest = new ServiceForTests(someService, anotherService);
    }

    @Test
    public void testMainProcess() {
        doReturn("Hello World!")
                .when(anotherService)
                .anotherProcess();

        classUnderTest.mainProcess();

        verify(someService)
                .process(any(String.class));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.