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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With