lundi 19 septembre 2016

How can I use Moq to test my Index action that returns list from the database?

I am learning to use unit testing and Moq for ASP.NET MVC 5. I am trying to write my first unit test for the index action of one of my controllers.

Here is the code for the index action.

[Authorize]
public class ExpenseController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: /Expense/
    public ActionResult Index()
    {
        return View(db.Expenses.ToList().Where(m => m.ApplicationUserId == User.Identity.GetUserId()));
    }
}

All I want to do is just check that the returned view is not null

Something like this

    [TestMethod]
    public void ExpenseIndex()
    {
        // Arrange
        ExpenseController controller = new ExpenseController();

        // Act
        ViewResult result = controller.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result);
    }

Of course, this is not working because of the connecting to the database and the using of the ApplicationUserId so would you guys help me to moq and unit test this action or recommend me a tutorial where I can get familiar with mocking in ASP.NET MVC.

Aucun commentaire:

Enregistrer un commentaire