私はSpring Cloudのeurekaとfeignを使用して、いくつかのサービス間で通信しています(AとBとしましょう)。ここで、単一のサービス (A) のサービス レイヤーを単体テストしたいと思います。問題は、このサービス (A) が偽のクライアントを使用して、他のサービス (B) の情報を要求していることです。
特別な構成なしで単体テストを実行すると、次の例外がスローされます: java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: service-b
=> しかし、サーバーを実行したくありません。
私の質問は次のとおりです:偽のクライアントをモックする方法はありますか?それで、eureka インスタンスとサービス (B) を実行せずにサービス (A) を単体テストできますか?
編集:偽のクライアント用のスタブを作成しました。スタブは、テスト内でスタブをインスタンス化するスプリングを強制するプライマリ コンポーネントとしてマークされています。
これが私が思いついた解決策です。
//the feign client
@FeignClient("user")
public interface UserClient {
UserEntity getUser();
}
//the implementation i use for the tests
@Component
@Primary //mark as primary implementation
public class UserClientTestImpl implements UserClient {
@Override public UserEntity getUser() {
return someKindOfUser;
}
}