How to mock method with ViewModel in MVC4 with Entity Framework 4.0

Erwin Rooijakkers

I want to test the following method:

public ActionResult Index()
{
    var transactions = db.Transactions.Include(t => t.User)
                            .GroupBy(t => t.UserId)
                            .Select(group => new TransactionViewModel
                            {
                                User = group.FirstOrDefault().User.FullName,
                                UserId = group.FirstOrDefault().UserId,
                                Total = (group.Sum(t => t.TransactionAmount))
                            });

    // Show lowest balance first
    return View(transactions.ToList());
}

Here the Transaction model has a list of Orders, has a foreign key to User and some more properties, see:

public class Transaction
{
    public int TransactionId { get; set; }
    public DateTime Date { get; set; }
    public int UserId { get; set; }
    public List<Order> Orders { get; set; }
    public decimal TransactionAmount { get; set; }
    public virtual User User { get; set; }
}

The TransactionViewModel looks as follows:

public class TransactionViewModel
{
    public string User { get; set; }
    public int UserId { get; set; }
    public decimal Total { get; set; }
}

and is used to calculate the Total of different transactions belonging to a user.

To test this method I have a FakeDbSet and use a FakeContext (which both work in tests of other controllers) in the following Setup:

[TestClass]
public class TransactionControllerTest
{
    TransactionController trController;

    [TestInitialize]
    public void TransactionControllerTestInitialize()
    {
        // Arrange 
        var memoryTransactionItems = new FakeDbSet<Transaction>
        {
           new Transaction {
               Date = DateTime.Today,
               TransactionAmount = 5.10M,
               UserId = 1,
               Orders = new List<Order>{
                    // Categorie 2 and confirmed
                    new Order { OrderId = 2, 
                                UnitPrice = 2.00M, 
                                Quantity = 1, 
                                Date = DateTime.Today, 
                                IsConfirmed = true, 
                                User = new User { 
                                    Name = "Kees", 
                                    FullName="Kees Piet", 
                                    Email = "[email protected]", 
                                    isAvailable = true, 
                                    UserId = 1 
                                }, 
                                Product = new Product {
                                    Category = new Category {
                                        CategoryId = 2, 
                                        Name = "Categorie2"
                                    }, 
                                    Name = "Testproduct2",
                                    Price = 2.00M,
                                    Visible = true
                                }
                    },
                    // Categorie 2 and confirmed
                    new Order { OrderId = 2, 
                                UnitPrice = 1.00M, 
                                Quantity = 1, 
                                Date = DateTime.Today, 
                                IsConfirmed = true, 
                                User = new User { 
                                    Name = "Jan", 
                                    FullName="Jan Piet", 
                                    Email = "[email protected]", 
                                    isAvailable = true, 
                                    UserId = 2 
                                }, 
                                Product = new Product {
                                    Category = new Category {
                                        CategoryId = 2, 
                                        Name = "Categorie2"
                                    }, 
                                    Name = "Testproduct2",
                                    Price = 3.10M,
                                    Visible = true
                                }
                    }
               }
           }
        };


        // Create mock units of work
        var mockData = new Mock<FakeContext>();
        mockData.Setup(m => m.Transactions).Returns(memoryTransactionItems);

        // Setup controller
        trController = new TransactionController(mockData.Object);
    }

    [TestMethod]
    public void TestTransactionIndex()
    {
        // Invoke
        var viewResult = trController.Index() as ViewResult;
        var transactionsFromView = (IEnumerable<TransactionViewModel>)viewResult.Model;

        // Assert
        Assert.AreEqual(1, transactionsFromView.Count(),
            "The amount of transactions added to the Index View should be 1.");
    }
}

When I run the TestTransactionIndex I get the following error:

Test Name: TestTransactionIndex Test Outcome: Failed Test Duration: 0:00:30.6276475

Result Message: Test method Tests.Controllers.TransactionControllerTest.TestTransactionIndex threw exception: System.NullReferenceException: Object reference not set to an instance of an object. Result StackTrace: at lambda_method(Closure , IGrouping2 ) at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Controllers.TransactionController.Index()

I find this strange since I setup my mock units in the proper way. I hope someone can explain how I can properly send the FakeDbSet<Transaction> to the view and not get a NullReferenceException.

/Edit As requested, here are the contructors for TransactionController:

private IContext _context;

public TransactionController()
{
    _context = new Context();
}

public TransactionController(IContext context)
{
    _context = context;
}
Daniel J.G.

The query in your index method includes the line:

db.Transactions.Include(t => t.User)

And the Select part of the query is using the User property in the Transaction class to populate the TransactionViewModel as in

User = group.FirstOrDefault().User.FullName,

That line will throw a NullReferenceException if the User property in the Transaction is null. So you need the result of that query to contain a not null User property when executed in your unit test using the fake objects.

I am not sure how your fake context and DbSets work, but the easiest thing to try is to populate the User property of the Transactions in your fake memoryTransactionItems.

You may also try adding a fake users dbset as in the next code snippet (I'm assuming you have a Users DbSet in your EF context):

var memoryUsers = new FakeDbSet<User>
{
    new User{ UserId = 1, ... },
    ...
};

mockData.Setup(m => m.Users).Returns(memoryUsers);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to mock method with ViewModel in MVC4 with Entity Framework 4.0

From Dev

MVC4 app - how to remove Entity Framework and implement SimpleMembershipProvider?

From Dev

PieChart in mvc4 from Entity Framework

From Dev

Dropdownlist and MVC4 Entity Framework

From Dev

How to initialize viewmodel in mvc4

From Dev

Log4net with Entity Framework 5 and MVC4

From Dev

How to retrieve image from database without using Entity Framework in ASP.NET MVC4

From Dev

How to retrieve image from database without using Entity Framework in ASP.NET MVC4

From Dev

How to perform edit function in MVC4 without using entity framework?

From Dev

Will Orchard CMS support MVC4 with Entity Framework

From Dev

MVC4 Entity Framework Controller Database Issue

From Dev

MVC4 Entity Framework 6 Model State Validation Issues

From Dev

How to implement IEnumerator in MVC4 application with ViewModel

From Dev

How can i create a Partial View for MVC4 or MVC 5 using Entity Framework (.edmx Model) with Razor Views?

From Dev

How to Mock MVC4 application when UI testing with Watin?

From Dev

Update entity in mvc4

From Dev

How to mock an interface for entity framework?

From Dev

MVC4 - How to call controller method from razor view

From Dev

Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

From Dev

Single or multiple DbContext File in mvc4 using Entity framework 6

From Dev

Assigning [Key] attribute to Entity Framework generated class - MVC4 C#

From Dev

MVC4 Code First Entity Framework Upload large files to a SQL Server database

From Dev

upload image in server folder and save path in Sqlserver using entity framework mvc4

From Dev

.NET Membership in ASP.NET MVC4 and Entity Framework with Oracle as Db

From Dev

Merging MVC4 membership database with entity framework code first database

From Dev

Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

From Dev

Unable to Use an HtmlHelper in Razor syntax in MVC4 Intranet App using Entity Framework

From Dev

Assigning [Key] attribute to Entity Framework generated class - MVC4 C#

From Dev

upload image in server folder and save path in Sqlserver using entity framework mvc4

Related Related

  1. 1

    How to mock method with ViewModel in MVC4 with Entity Framework 4.0

  2. 2

    MVC4 app - how to remove Entity Framework and implement SimpleMembershipProvider?

  3. 3

    PieChart in mvc4 from Entity Framework

  4. 4

    Dropdownlist and MVC4 Entity Framework

  5. 5

    How to initialize viewmodel in mvc4

  6. 6

    Log4net with Entity Framework 5 and MVC4

  7. 7

    How to retrieve image from database without using Entity Framework in ASP.NET MVC4

  8. 8

    How to retrieve image from database without using Entity Framework in ASP.NET MVC4

  9. 9

    How to perform edit function in MVC4 without using entity framework?

  10. 10

    Will Orchard CMS support MVC4 with Entity Framework

  11. 11

    MVC4 Entity Framework Controller Database Issue

  12. 12

    MVC4 Entity Framework 6 Model State Validation Issues

  13. 13

    How to implement IEnumerator in MVC4 application with ViewModel

  14. 14

    How can i create a Partial View for MVC4 or MVC 5 using Entity Framework (.edmx Model) with Razor Views?

  15. 15

    How to Mock MVC4 application when UI testing with Watin?

  16. 16

    Update entity in mvc4

  17. 17

    How to mock an interface for entity framework?

  18. 18

    MVC4 - How to call controller method from razor view

  19. 19

    Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

  20. 20

    Single or multiple DbContext File in mvc4 using Entity framework 6

  21. 21

    Assigning [Key] attribute to Entity Framework generated class - MVC4 C#

  22. 22

    MVC4 Code First Entity Framework Upload large files to a SQL Server database

  23. 23

    upload image in server folder and save path in Sqlserver using entity framework mvc4

  24. 24

    .NET Membership in ASP.NET MVC4 and Entity Framework with Oracle as Db

  25. 25

    Merging MVC4 membership database with entity framework code first database

  26. 26

    Entity Framework profiler - ASP.NET MVC4 with EF 6 -Unable to determine the provider name

  27. 27

    Unable to Use an HtmlHelper in Razor syntax in MVC4 Intranet App using Entity Framework

  28. 28

    Assigning [Key] attribute to Entity Framework generated class - MVC4 C#

  29. 29

    upload image in server folder and save path in Sqlserver using entity framework mvc4

HotTag

Archive