Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq Parent does not have a default constructor. The default constructor must be explicitly defined

I am using entity framework db first approach and generated edmx file.

I am trying to implement enter code here Unit testing with MOQ framework.

Here is my code

[TestMethod]
    public void DeleteApplication()
    {
        var mockContext = new Mock<ARMSContext>();
        var data = GetMemoryApplications();
        var mockSet = new Mock<DbSet<Application>>();
        mockSet.As<IQueryable<Application>>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<Application>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<Application>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<Application>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        var test=appcontroller.Delete(1, 1);

    }

I am getting the Parent does not have.. exception while calling mockSet.Object.

could you pls to resolve this exception?

like image 502
Prakash Rajendran Avatar asked Nov 10 '22 07:11

Prakash Rajendran


1 Answers

From what you have given, I can't see how you are using Mock<DbSet<Application>>, nor Mock<ARMSContext>.

Here is the sample given from MSDNs "Testing with a mocking framework (EF6 onwards)", which hooks the DbSet up to the Context:

    [TestMethod]
    public void GetAllBlogs_orders_by_name()
    {
        var data = new List<Blog>
        {
            new Blog { Name = "BBB" },
            new Blog { Name = "ZZZ" },
            new Blog { Name = "AAA" },
        }.AsQueryable();

        var mockSet = new Mock<DbSet<Blog>>();
        mockSet.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        var mockContext = new Mock<BloggingContext>();
        mockContext.Setup(c => c.Blogs).Returns(mockSet.Object);

        var service = new BlogService(mockContext.Object);
        var blogs = service.GetAllBlogs();

        Assert.AreEqual(3, blogs.Count);
        Assert.AreEqual("AAA", blogs[0].Name);
        Assert.AreEqual("BBB", blogs[1].Name);
        Assert.AreEqual("ZZZ", blogs[2].Name);
    }
}
like image 186
Dominic Zukiewicz Avatar answered Nov 14 '22 21:11

Dominic Zukiewicz