如何对在基类中调用方法的方法进行单元测试?

时间:2018-02-02 19:45:47

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

我正在使用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");

直到基本方法调用为止。我应该以某种方式提供模拟响应吗?你会怎么做这个测试?感谢。

1 个答案:

答案 0 :(得分:1)

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