【问题标题】:How can I unit test a method that calls a method in a base class?如何对调用基类中的方法的方法进行单元测试?
【发布时间】:2018-02-02 19:45:47
【问题描述】:

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

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 在基类中,它调用数据库。我该如何进行测试?到目前为止,我有以下内容:

[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");

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

【问题讨论】:

  • 你会模拟依赖,即数据库,以返回一个假值。
  • 你知道如果它在基类中我将如何设置方法吗?
  • 基类是如何获得db依赖的?您只需要为您的PosPortalApiService 提供模拟依赖项。实现在基类中的事实并不重要。

标签: asp.net unit-testing asp.net-web-api moq xunit


【解决方案1】:

您可以通过将PosPortalApiService 对象设为部分模拟来模拟基类中的方法(假设它是virtualabstract)。 (部分模拟将使用真实的类行为,除了你模拟出来的部分)。您可以通过在模拟对象上设置 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");

【讨论】:

  • 这正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多