How to cover using Mock and C#?

Question:

I need to cover for the method example below:

public int GetQtdCart()
{
    int qtCart = 0;
    using (var db = new SfrEntities())
    {
        qtCarteira = db.Set<Contract>().Select(x => x.Cart).Distinct().Count();
    }
    return qtCart;
}

I created a test layer and applied the NUnit and Pex.Microsoft.Framework references.

I created the test below which is successful but the coverage is zero:

    public void TestarGetQtdCart()
    {
        Mock<IContratoRepository> mock = new Mock<IContratoRepository>();
        mock.Setup(m => m.GetQtdCart()).Returns(contrato.Carteira);
        var resultadoEsperado = mock.Object.GetQtdCart();
        var resultado = 0;

        Assert.AreEqual(resultado, resultadoEsperado);
    }

Answer:

Sorted out. Below is the test I used:

    public void TestarGetQtdCarteira()
    {
        var mockSet = new Mock<DbSet<Contrato>>();
        mockSet.As<IList<Contrato>>().Setup(m => m.Count).Returns(contrato.Carteira);

        var mockContext = new Mock<PrgEntities>();
        mockContext.Setup(c => c.Contrato).Returns(mockSet.Object);

        var service = new ContratoRepository(mockContext.Object);
        var contratos = service.GetQtdCarteira();

        Assert.AreEqual(contrato.Carteira, contratos);
    }
Scroll to Top