我如何对调用基础 class 中的方法的方法进行单元测试?

How can I unit test a method that calls a method in a base class?

我正在使用 Moq 将依赖项传递给我需要测试的 class。这是要测试的构造函数和方法:

public class PosPortalApiService : PosPortalApiServiceBase, IPosPortalApiService {


    private readonly string _apiEndpoint;

    public PosPortalApiService ( IDependencyResolver dependencyResolver,
                                 IOptions<AppSettings> appSettings ) : base    ( dependencyResolver ) {
        _apiEndpoint = appSettings.Value.ApiEndpoint;
    }

public async Task<IEnumerable<IStore>> GetStoresInfo ( string userId ) {
        var endpoint = GetEndpointWithAuthorization(_apiEndpoint + StoresForMapEndpoint, userId);
        var encryptedUserId = EncryptionProvider.Encrypt(userId);

        var result = await endpoint.GetAsync(new {
            encryptedUserId
        });

        return JsonConvert.DeserializeObject<IEnumerable<Store>>(result);
    }

GetEndpointWithAuthorisation 在基础 class 中,它调用数据库。我该如何进行测试?到目前为止我有以下内容:

[Fact]
    public void GetStoresInfoReturnsStoresForUser()
    {

        var mockHttpHandler = new MockHttpMessageHandler();
        var mockHttpClient = new HttpClient(mockHttpHandler);
        //mockHttpHandler.When("http://localhost/api/select/info/store/*")
        //                .Respond("application/json",  );
        AppSettings appSettings = new AppSettings() { ApiEndpoint = "http://localhost" };
        var encryptedUserId = EncryptionProvider.Encrypt("2");                       
        var mockDependancyResolver = new Mock<IDependencyResolver>();

        var mockIOptions = new Mock<IOptions<AppSettings>>();
        IOptions<AppSettings> options = Options.Create(appSettings);
        //Arrange
        PosPortalApiService ApiService = new PosPortalApiService(mockDependancyResolver.Object, options);

        var sut = ApiService.GetStoresInfo("2");

它一直运行到基本方法调用。我应该以某种方式提供模拟响应吗?你会如何处理这个测试?谢谢

您可以通过使 PosPortalApiService 对象成为部分模拟来模拟基础 class 中的方法(假设它是 virtualabstract)。 (部分模拟将使用真实的 class 行为,除了您模拟的部分)。您可以通过在模拟对象上设置 CallBase = true 来做到这一点;

var ApiServiceMock = new Mock<PosPortalApiService>(mockDependancyResolver.Object, options) 
                    {CallBase = true};

ApiServiceMock.Setup(x => x.GetEndpointWithAuthorisation(It.IsAny<string>(), It.IsAny<string>())
              .Returns(someEndpointObjectOrMockYouCreatedForYourTest);

PosPortalApiService ApiService = ApiServiceMock.Object;
var sut = ApiService.GetStoresInfo("2");