How to cover using Mock and C#?

Asked

Viewed 55 times

3

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 references NUnit and Pex.Microsoft.Framework.

I created the test below that 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);
    }
  • this is the site of the OS in Portuguese, translate your question

  • Coverage is zero because it doesn’t test the Getqtdcart method().

1 answer

0

Solved. 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);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.