Expected call to layout once, but was 2 times: m => m.SaveChanges (), UnitTest

Please, I am 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 check the addUrl of the class above. I am trying to implement as described 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 suspect I am binding the EFDContext, but I have no idea how. I am not sure where I am going wrong. Any help would be appreciated.

+3


source to share


1 answer


In a method, AddUrl

you call the method twice SaveChanges

. To test this behavior, you need to change:

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

      

IN:



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

      

You can read about Times

options here

+5


source







All Articles