jeudi 5 novembre 2015

Moq test delete

i'm trying to make a test in my example projet, and i'm getting an error when i assert if the deleted object is null(Assert.IsNull failed).

I'm using Microsoft Visual Studio 2010, Entity Framework 4.3.1 and regular Moq.

Here is the code i'm using:

Service:

    private ClientRepository rep; 

    public ClientService(MyContext ctx)
    {
        this.rep = new ClientRepository(ctx);
    }

public void Delete(Client client)
    {
        try
        {
            rep.Delete(client);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            throw new Exception("error"); 
        }
    }

public Client GetById(int Id)
    {
        return rep.GetById(Id);
    } 

Repository:

    private MyContext _dbContext;

    public ClientRepository(MyContext ctx)
    {
        _dbContext = ctx;
    }

public void Delete(Client client)
    {
        Client cl = _dbContext.Clients.Where(x => x.Id == client.Id).FirstOrDefault();
        if (cl != null)
        {
            _dbContext.Clients.Remove(client);
            _dbContext.SaveChanges();
        }
        else
        {
            throw new Exception("Client does'n exist");
        }
    }

public Client GetById(int Id)
    {
        return _dbContext.Clients.Where(x => x.Id == Id).FirstOrDefault();
    }

My Delete Test:

 [TestMethod]
    public void MockDelete()
    {
        //arrange
        var data = new List<Client> 
        {
            new Client(){
                Id = 1,
                Name = "asdfg"
            }
        }.AsQueryable();

        var dbSetMock = new Mock<IDbSet<Client>>();
        var myContextMock = new Mock<MyContext>();

        dbSetMock.As<IQueryable<Client>>().Setup(m => m.Provider).Returns(data.Provider);
        dbSetMock.As<IQueryable<Client>>().Setup(m => m.Expression).Returns(data.Expression);
        dbSetMock.As<IQueryable<Client>>().Setup(m => m.ElementType).Returns(data.ElementType);
        dbSetMock.As<IQueryable<Client>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        myContextMock.Setup(m => m.Clients).Returns(dbSetMock.Object);

        var service = new ClientService(myContextMock.Object);

        //act
        var classtodelete = data.First(m => m.Id == 1);
        service.Delete(classtodelete);

        string name = service.GetById(1).Name;

        //assert
        dbSetMock.Verify(m => m.Remove(It.IsAny<Client>()), Times.Once());
        myContextMock.Verify(m => m.SaveChanges(), Times.Once);

        Assert.IsNull(name);
    }

My goal is to test the business rules of my Service(i didn't put here), maybe i mocked the wrong classes, or i'm missing something, i hope someone can help me.

Aucun commentaire:

Enregistrer un commentaire