英文:
How to mock default method of unimplemented interface?
问题
I can provide the translation of the code-related content:
在进行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() {
//设置Retrofit...
}
}
在另一个服务类中:
public class DemoUser {
public void doUserBusiness(String userId) {
User user = UserService.getService().getUserById(userId);
//在这里执行业务逻辑
}
}
然后,您如何在测试doUserBusiness
方法时模拟UserService.getService().getUserById(userId);
以返回一个模拟用户呢?
英文:
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
得分: 0
你可以尝试使用 mockStatic()
,示例代码如下:
try (MockedStatic<UserService> serviceMockedStatic = mockStatic(UserService.class)) {
serviceMockedStatic
.when(() -> UserService.getService().getUserById(userId))
.thenReturn(any());
}
更多信息请查看这里:staticMock
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论