使用MOQ进一步验证结果

时间:2016-05-10 18:53:33

标签: c# .net moq

我有以下代码

public bool IsUnitAvailable()
        {
            this.isUnitAvailable = false;
                if(isUnitAvailable == false)
                {
                    var exception = new Exception("Unit Unavailable");
                    exception.Data.Add("Quotation","1234567");
                    exception.Data.Add("propertyDate", "2016-10-10");                        this.GetElmahExtensionWrapper().LogToElmah(exception);
                }
            }    
            return this.isUnitAvailable;
        }            

以及以下单元测试。

[TestMethod]    
    public void WhenUnitIsNotAvailableExceptionShouldBeLoggedInElmahTest()
    {
        //Arrange
        var iPricingServiceMock = new Mock<IPricingService>(MockBehavior.Strict);
        iPricingServiceMock.Setup(
            counter => counter.IsUnitAvailableOn(It.IsAny<Unit>(),It.IsAny<DateTime>())).Returns(false);

        var mockElmahExtensionWrapper = TestHelper.mk.GetMock<IElmahExtensionWrapper>();

        // act
        var quotation = new Quotation();
        quotation.SetElmahExtensionWrapper(mockElmahExtensionWrapper.Object);
        quotation.IsUnitAvailable();

        //assert
        mockElmahExtensionWrapper.Verify(counter => counter.LogToElmah(It.IsAny<Exception>()), Times.Exactly(1));
//change the test to verify that the exception that was logged had 2 Data properties?
    }

单元测试工作正常。如何更改测试以验证记录的异常是否具有2个数据属性?将代码更改为以下内容会引发&#34;无法解析符号数据属性&#34;错误。

mockElmahExtensionWrapper.Verify
                (
                    counter => counter.LogToElmah
                    (
                        It.IsAny<Exception>(ex=>ex.Data.Count == 2)
                    ), 
                    Times.Exactly(1) 
                );

enter image description here

1 个答案:

答案 0 :(得分:2)

将验证更改为:

 mockElmahExtensionWrapper.Verify(counter => counter.LogToElmah(It.Is<TraceException>(ex => ex.Data["Quotation"] == "1234567" && ex.Data["propertyDate"] == "2016-10-10"), Times.Exactly(1));