验证单元测试中是否调用了方法

loo*_*oop 15 c# tdd unit-testing moq

我有一个单元测试我正在检查一个方法是否被调用一次,所以我尝试这样: -

这是我的ILicenseManagerService模拟,我通过construstor传递它的对象.

public Mock<ILicenseManagerService> LicenseManagerService { get { return SetLicenseManagerServiceMock(); } }

    private Mock<ILicenseManagerService> SetLicenseManagerServiceMock()
    {
        var licencemangerservicemock = new Mock<ILicenseManagerService>();
        licencemangerservicemock.Setup(m => m.LoadProductLicenses()).Returns(ListOfProductLicense).Verifiable();

        return licencemangerservicemock;
    }

    public static async Task<IEnumerable<IProductLicense>> ListOfProductLicense()
    {
        var datetimeoffset = new DateTimeOffset(DateTime.Now);

        var lst = new List<IProductLicense>
        {
            GetProductLicense(true, datetimeoffset, false, "1"),
            GetProductLicense(true, datetimeoffset, false, "2"),
            GetProductLicense(true, datetimeoffset, true, "3")
        };

        return lst;
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用这个模拟对象来设置_licenseManagerService并在测试中的方法中调用LoadProductLicenses().像这样.许可证即将到期.

var licenses = (await _licenseManagerService.LoadProductLicenses()).ToList();
Run Code Online (Sandbox Code Playgroud)

我尝试验证对此方法的调用 -

 LicenseManagerService.Verify(m => m.LoadProductLicenses(),Times.Once);
Run Code Online (Sandbox Code Playgroud)

但是,当我运行我的单元测试异常时,说方法根本没有被调用.我在哪里做错了?

编辑 @dacastro我在这里调用相同的模拟是我的单元测试.

[TestMethod]
    [TestCategory("InApp-InAppStore")]
    public async Task return_products_from_web_when_cache_is_empty()
    {
        // this class basically for setting up external dependencies
        // Like - LicenceManagerService in context, i am using this mock only no new mock.
        var inAppMock = new InAppMock ();                  


        // object of Class under test- I used static method for passing external         
        //services for easy to change 
        var inAppStore = StaticMethods.GetInAppStore(inAppMock);

        // method is called in this method
        var result = await inAppStore.LoadProductsFromCacheOrWeb();

        // like you can see using the same inAppMock object and same LicenseManagerService
        inAppMock.LicenseManagerService.Verify(m => m.LoadProductLicenses(),Times.Once);


    }
Run Code Online (Sandbox Code Playgroud)

dca*_*tro 21

LicenseManagerService.Verify(m => m.LoadProductLicenses(),Times.Once);
Run Code Online (Sandbox Code Playgroud)

通过调用该LicenseManagerService属性,您将创建一个新的模拟对象.当然,在这个实例上从未进行任何调用.

您应该更改此属性的实现,以便在每次调用时返回相同的实例.