如何在客户端接口中注入 Mockito 服务层

how to inject Mockito service layer in clientside interface

@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 接口时。

Mockito.when(userClient.query(UUID.fromString("s8yt544-sadsa4-sda-dfds-hfdsfsjfs8"), null, null).getBody()).thenReturn(userResponse);

我认为,您的问题在 .getBody() 部分。设置模拟时,您应该编写预期的方法调用和预期的结果。因此,预期的方法调用是 .query() 方法,我猜预期的结果是 userResponse.

参见 @MockBean docs which allow you to use Mockito deep stubs

    @MockBean(answer = RETURNS_DEEP_STUBS)
    private TwinApiUserClient userClient;

这允许您模拟像 a().b().c() 这样的调用链的结果,这就是您在此处尝试的结果。