在模拟上预期调用一次,但是Moq是0次

时间:2016-04-21 14:57:59

标签: c# unit-testing moq

我收到错误

  

在模拟上调用一次,但是0次

以下是我的代码结构

public class GenerateAddress : IGenerateAddress 
{
    public GenerateAddress(IAddress createAdd, IValidate validate) {
       //constructor 
    }

    public Address GetAddressFromA(string name){..}
}

public class SaveAddress : ISaveAddress 
{
    public SaveAddress(IGenerateAddress generateaddress) {
        //constructor 
    }

    public bool Save(string name)
    {
        var address = generateaddress.GetAddressFromA(name);
        ......
        //Rest of the code to save 
    }
}

测试类SaveAddress的测试方法

public void TestVerifyGetAddressIsCalled()
{
    var mockIAddress = new Mock<IAddress>();
    var mockValidate = new Mock<IValidate>();

    var genAddress = new Mock<IGenerateAddress>();

    var objGenAdress = new GenerateAddress(mockIAddress.Object, mockValidate.Object) // 

    var objSaveAddress = new SaveAddress(objGenAdress);

    objSaveAddress.Save("dddd");

    //Verify if IGenerateAddress 'GenerateAddress' is called

    genAddress.Verify(a=>a.GenerateAddress("ddddd"),Times.Once); // Throws Excepted Invocation 
}

我需要验证是否调用GenerateAddress。我也做了Setup并为 Address 对象分配了值,但即使这些值也没有设置。不确定出了什么问题。

3 个答案:

答案 0 :(得分:3)

看起来你正在用'dddd'(4 d's)调用Save,但验证它是用'ddddd'(5 d's)调用的。

将实际数据放在变量中并在两种情况下引用它都更安全:

var name = "dddd";
objSaveAddress.Save(name);

genAddress.Verify(a=>a.GenerateAddress(name),Times.Once);

答案 1 :(得分:2)

您正在使用IGenerateAddress手动创建的objGenAdress SaveAddress而不是模拟的genAddress

另外,假设SUT是只需SaveAddress的{​​{1}},则不需要其他模拟。

IGenerateAddress

答案 2 :(得分:1)

我认为在选择回复后,如果我们重构代码首先创建SaveAddress类作为模拟并传递参数genAddress,并将CallBase属性设置为true。此属性的默认值为false。如果你不使用这个参数,你的方法调用返回null,你得到this.post标题错误。

        var genAddress = new Mock<IGenerateAddress>();

        var objSaveAddress = new Mock<SaveAddress>(genAddress.Object){CallBase = true};

        var name = "dddd";

        //Act
        objSaveAddress.Object.Save(name);

        //Assert
        //Verify if IGenerateAddress 'GenerateAddress' is called    
        genAddress.Verify(a => a.GetAddressFromA(name), Times.Once);