简体   繁体   中英

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);
    }

but I am getting a null pointer exception. when trying to initialize the TwinApiUserClient Interface through Mockito hardcode.

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

I think, your problem in .getBody() part. When you setup your mocks you should write expected method call and expected result. So, expected method call is .query() method and expected result, I guess, is userResponse .

See @MockBean docs which allow you to use Mockito deep stubs

    @MockBean(answer = RETURNS_DEEP_STUBS)
    private TwinApiUserClient userClient;

This allows you to mock the result of a chain of calls like a().b().c() which is what you have attempted here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM