I write a unit test using xunit and Moq in asp.net core, i follow this Article for this, but i got this error:
Invalid setup on a non-virtual (overridable in VB) member: m => m.Blogs
this is what i tried:
[Fact]
public void CreateBlog()
{
var mockDbSet = new Mock<DbSet<Blog>>();
var mockContext = new Mock<Context>();
mockContext.Setup(m => m.Blogs).Returns(mockDbSet.Object); //In this line i got error
var service = new BlogController(mockContext.Object);
service.AddBlog("ADO.NET Blog", "adtn.com");
mockDbSet.Verify(m => m.Add(It.IsAny<Blog>()), Times.Once());
mockContext.Verify(m => m.SaveChanges(), Times.Once());
}
these are my models class:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public virtual IList<Post> Posts { get; set; }
}
and:
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime RegisterDate { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
and this is my controller:
public class BlogController : Controller
{
private readonly Context _context;
public BlogController(Context ctx)
{
_context = ctx;
}
[HttpPost]
public Blog AddBlog(string name, string url)
{
var blog = new Blog() { Name = name, Url = url };
_context.Blogs.Add(blog);
_context.SaveChanges();
return blog;
}
}
UPDATE: I make dbset in the context virtual, but it gives another error:
Can not instantiate proxy of class: EntitFrameworkCore.Models.Context
what is the problem?