如何在 Spring Boot 中模拟另一个服务中的方法

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

对于上下文,我有 2 个服务类, ValService 和 AppService,

在 ValService 中我有一个方法 validate ,它调用 AppService 中的方法

 Character c = appService.sendToAPI(listOfString, stringId);

sendToAPI 方法调用返回字符的外部 API。

现在,为了测试 ValService,我如何正确模拟该方法?

spring spring-boot mockito junit5 spring-test
1个回答
0
投票

恕我直言,我会像这样测试它

@ExtendWith(MockitoExtension.class)
public class MyTest{
       @Mock
       AppService appService;
       
       @InjectMocks
       ValService valService;
      
       @Test
       void testValidation() {
           when(appService.sendToApi(any(), any())).thenReturn(getMeReturnChar());
           
           final var result = valService.validate("someData");

           assertThat(result).equalTo("myValidationSign");
    
       }
       
       private Character getMeReturnChar() {
           return 'testingCharacterOfYourChoice';
       }
}

但这只是一个粗略的例子。我需要更多信息来进一步帮助您

© www.soinside.com 2019 - 2024. All rights reserved.