我正在动手使用Junit/Mockito/PowerMockito
我有一个接口类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 ...
}
}
在其他服务中:
public class DemoUser {
public void doUserBusiness(String userId) {
User user = UserService.getService().getUserById(userId);
//do business logic here
}
}
那么,在测试doUserBussiness
方法时,我如何模拟UserService.getService().getUserById(userId);
以返回一个模拟用户?
您可以尝试使用mockStatic()
:
try (MockedStatic<UserService> serviceMockedStatic = mockStatic(UserService.class)) {
serviceMockedStatic
.when(() -> UserService.getService().getUserById(userId))
.thenReturn(any());
}
更多信息在这里->staticMock