0

I'm doing some hands on with Junit/Mockito/PowerMockito

I have an interface class

import retrofit2.Call;
import com.learning.model.user.User;
import java.io.IOException;

public interface UserService {
        @GET("/serviceUser/{userId}")
        Call<User> getUser(@Path("userId") String userId);
    
        default User getUserById(String userId) {
            try {
                return getUser(userId).execute().body();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        static UserService getUserService(){
            //setup retrofit ...
        }
}

In another service:

public class DemoUser {
    public void doUserBusiness(String userId) {
        User user = UserService.getService().getUserById(userId);
        //do business logic here
    }
}

Then how can I mock the UserService.getService().getUserById(userId); to return a mock user when testing the doUserBussiness method?

1 Answer 1

0

You can try to use mockStatic() like:

try (MockedStatic<UserService> serviceMockedStatic = mockStatic(UserService.class)) {
     serviceMockedStatic
         .when(() -> UserService.getService().getUserById(userId))
         .thenReturn(any());
}

More here -> staticMock

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.