user3852419
user3852419

Reputation: 31

unit testing controller method in c#

I am trying to unit test a controller method create I want to test if the data is saved to the database, I have created a Model class called Person where I have attributes such as person name, last name, email and age

public class Person
{
    [Key]
    public int PersonID { get; set; }

    [Display(Name = "Name")]
    [Required]
    public string  name { get; set; }

    [Display(Name = "Last Name")]
    [Required]
    public string  lastName { get; set; }

    [Display(Name = "Email")]
    [Required]
    public string  email { get; set; }

    [Display(Name = "Age")]
    [Required]
    public int age { get; set; }
}

Then I have my controller method Create that I want to test whether it is saving on the database or not.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonID,name,lastName,email,age")] Person person)
{
    if (ModelState.IsValid)
    {
        db.MyPersons.Add(person);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(person);
}

Upvotes: 2

Views: 122

Answers (1)

When you say you want to unit test a controller method - do you really mean unit test or are you thinking of an integration test? Both test types are valid.

Unit testing your controller method would probably result in a couple of different test:

* Check if the posted result matches the Create method (does the binding work)
* Check is the ModelState is valid for a correct post and invalid for an incorrect one
* Check if the person is added to the collection and if the collection is saved (these tests are implementation specific and it looks like you're using an orm framework for this and verifying the orm works is not a task you should perform)
* Check if the correct view is returned with the correct data

You might want more than one unit test per testcase i listed btw.

If you really want an integration test, you probably just want to check if the data was persisted to the database. This probably requires you to do a setup for your test scenario where you create an empty database and then verify by getting the data out of the db aftwards and checking the values. Remember that starting with a fresh/empty database for each test is the only way of making the test truly independant on each other - this will help you in the long run when more and more tests are added and when the project grows old and you forget what/how the other tests are made.

Upvotes: 1

Related Questions