gpt4 book ai didi

java - 如何在客户端接口(interface)中注入(inject)Mockito服务层

转载 作者:行者123 更新时间:2023-12-01 21:24:16 31 4
gpt4 key购买 nike

@Service
public class UserServiceImpl implements UserService {

@Autowired
private TwinApiUserClient userClient; //client side interface we get the data through some queries
public TwinCollectionUserResponse getUserIds() {
return userClient.query(UUID.fromString("s8yt544-sadsa4-sda-dfds-hfdsfsjfs8"), null, null).getBody();
}

UserSerivceTest.class

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserSerivceTest{

@Autowired
private UserServiceImpl UserService;

@MockBean
private TwinApiUserClient userClient;

@Test
public void testGetTwins() {
TwinUsernResponse userResponse = this.getTwinUserResponse();//here userResponse is hard coded
Mockito.when(userClient.query(UUID.fromString("s8yt544-sadsa4-sda-dfds-hfdsfsjfs8"), null, null).getBody()).thenReturn(userResponse);
assertThat(UserService.getUserIds()).isEqualTo(userResponse);
}

但是我遇到了空指针异常。当尝试通过 Mockito 硬编码初始化 TwinApiUserClient 接口(interface)时。

最佳答案

参见@MockBean允许您使用 Mockito deep stubs 的文档

    @MockBean(answer = RETURNS_DEEP_STUBS)
private TwinApiUserClient userClient;

这允许您模拟一系列调用的结果,例如您在此处尝试的a().b().c()

关于java - 如何在客户端接口(interface)中注入(inject)Mockito服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837782/

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