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

时间:2014-06-25 07:44:09

标签: c# unit-testing tdd 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;
    }

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

var licenses = (await _licenseManagerService.LoadProductLicenses()).ToList();

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

 LicenseManagerService.Verify(m => m.LoadProductLicenses(),Times.Once);

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

编辑 @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);


    }

1 个答案:

答案 0 :(得分:15)

LicenseManagerService.Verify(m => m.LoadProductLicenses(),Times.Once);

通过调用LicenseManagerService属性,您可以创建模拟对象。当然,在这个实例上从未进行任何调用。

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