lundi 1 février 2016

Verifying a virtual method (MOQ)

So I am new to TDD and here is my problem:

I have a class with several methods. Something like this:

public class CompanyService : ICompanyService
{
    public ICompanyRepository companyRepository;
    public CompanyService() : this(new CompanyRepository())
    {                
    }

    public CompanyService(ICompanyRepository repository)
    {
        companyRepository = repository;
    }


    public virtual bool InsertCompany(Company company)
    {   
        return companyRepository.InsertCompany(company);
    }

    public bool InsertCompany(Company company, int total)
    {
        if (AddTotals(total))
        {
            return this.InsertCompany(company);
        }

        return false;
    }


    /// <summary>
    /// Wrapper for the static method at static service
    /// </summary>
    /// <param name="total"></param>
    /// <returns></returns>
    public virtual bool AddTotals(int total)
    {
        return StaticService.AddTotals(total);
    }
}

Most of my tests run fine for this class. So here is my unit test:

    [TestMethod]
    public void Test_Unit_AddTotals()
    {
         var service = new CompanyService();
         Assert.IsFalse(service.AddTotals(1));
    }


    [TestMethod]
    public void Test_Unit_InsertCompany_IsExecuted()
    {
        Guid id = GenerateCustomerID();
        var company = new Company { CustomerID = id, CompanyName = "CFN-" + id };
        var mock = new Mock<CompanyService>();
        mock.Setup(t => t.AddTotals(It.IsAny<int>())).Returns(true);
        mock.Object.InsertCompany(company, 1);
        mock.Verify(t => t.InsertCompany(It.IsAny<Company>()),Times.Once);
    }

    [TestMethod]
    public void Test_Unit_InsertCompany_IsSuccess()
    {
        Guid id = GenerateCustomerID();
        var company = new Company { CustomerID = id, CompanyName = "CFN-" + id };
        var mock = new Mock<CompanyService>();
        mock.Setup(t => t.AddTotals(It.IsAny<int>())).Returns(true);
        mock.Setup(t => t.InsertCompany(It.IsAny<Company>(), It.IsAny<int>())).Returns(true);
        Assert.IsTrue(mock.Object.InsertCompany(company, 1));
    }

    [TestMethod]
    public void Test_Unit_StaticService()
    {
        var rep = new Mock<ICompanyRepository>();
        rep.Setup(t => t.InsertCompany(It.IsAny<Company>())).Returns(true);

        var serviceMock = new Mock<ICompanyService>();
        serviceMock.Setup(t => t.AddTotals(It.IsAny<int>())).Returns(true);

        Assert.IsTrue(serviceMock.Object.AddTotals(0));
    }

    private Guid GenerateCustomerID()
    {
        return Guid.NewGuid();
    }

So when I make my 2 parameter InsertCompany method virtual my IsExecuted method fails at Verify, if I make it non-virtual, then I can't mock it for IsSuccess method and it fails..

Could you please tell me what I am missing with your TDD expertise?

Aucun commentaire:

Enregistrer un commentaire