Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected invocation on the mock once, but was 2 times: m => m.SaveChanges() , UnitTest

Please i m having trouble testing this method .

public class EFUrlRepository : IUrlsRepository
{
     public EFDbContext context = new EFDbContext();
     private Security security = new Security();
     public IQueryable<Url> Urls
     {
        get { return context.Urls; }
     }

     public bool AddUrl(Url url)
     {
          if(url.UrlId == 0)
          {
              context.Urls.Add(url);
              context.SaveChanges();
              url.UrlCode = security.Encrypt(url.UrlId.ToString());
              context.SaveChanges();
              return true;
          }
          return false;
     }
}

I am trying to test the addUrl of the class above. I try to implement as explained Here

[TestMethod]
public void CreateUrl_saves_a_url_via_context()
{
    var mockSet = new Mock<DbSet<Url>>();
    var mockContext = new Mock<EFDbContext>();
    mockContext.Setup(m => m.Urls).Returns(mockSet.Object);

    var repository = new EFUrlRepository();
    Url url = new Url() 
                     {  
                         UrlCode = "TYUyR", 
                         OriginalUrl = "https://fluentvalidation.com", 
                         IpAddress = "127.0.0.1", 
                         PostedDate = DateTime.Now 
                     };
    repository.context = mockContext.Object;


    repository.AddUrl(url);

    mockSet.Verify(m => m.Add(It.IsAny<Url>()), Times.Once());
    mockContext.Verify(m => m.SaveChanges(), Times.Once());
}

My test fails and throws the exception mentioned in the title above. Please What could be the problem. I am suspecting my EFDContext binding but i dont know how to go about it. I am not sure where i go wrong. Any help would be appreciated.

like image 616
brickleberry Avatar asked Jul 20 '15 18:07

brickleberry


1 Answers

In the method AddUrl you call the method SaveChanges twice. To verify this behaviour you need to change:

mockContext.Verify(m => m.SaveChanges(), Times.Once());

Into:

mockContext.Verify(m => m.SaveChanges(), Times.Exactly(2));

You can read about Times options here

like image 82
Old Fox Avatar answered Oct 01 '22 13:10

Old Fox