如何模拟未实现接口的默认方法?

huangapple go评论58阅读模式
英文:

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(&quot;/serviceUser/{userId}&quot;)
    	Call&lt;User&gt; getUser(@Path(&quot;userId&quot;) 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&lt;UserService&gt; serviceMockedStatic = mockStatic(UserService.class)) {
     serviceMockedStatic
         .when(() -&gt; UserService.getService().getUserById(userId))
         .thenReturn(any());
}

More here -> staticMock

huangapple
  • 本文由 发表于 2023年4月11日 09:58:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981899.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定