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?
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