There are many places where a NRE could occur in your code. For example the db
variable that is used in your controller action might be null. Make sure that it is initialized. Also in your unit test you have the following call var Comp = (Company)result.ViewData.Model;
. This could be null if there's no Company with id = 97 in your database. And then you attempt to compare the name Assert.AreEqual("TName", Comp.Name);
. But if Comp
is null this will throw an exception. Also in your unit test you are using some oCompanyController
variable which is unclear where it got initialized.
The correct way to unit test some code is to unit test it in isolation. This means that your code should be written with abstractions in mind. It should not depend on actual implementations. It is unclear what the db
variable is in your controller but it should be of some interface type (or abstract class) that you could mock in your unit test. This way you will achieve unit testing in isolation of the different layers. In this example you are unit testing a controller action, so the code in this controller should not depend on concrete classes.
Let's have an example of how your controller code might look like:
public class CompaniesController: Controller
{
public readonly ICompaniesRepository repository;
public CompaniesController(ICompaniesRepository repository)
{
this.repository = repository;
}
[SessionFilterAction]
public ViewResult Details(int id)
{
Company company = this.repository.GetCompanyById(id);
return View(company);
}
}
Now you could use a mocking framework such as Moq, NSubstitute or Rhino.Mocks to mock the repository in your unit test and be able to define expectations. For example with NSubstitute:
[TestMethod]
public void Company_Details2()
{
// arrange
var repository = Substitute.For<ICompaniesRepository>();
var id = 97;
var company = new Company();
repository.GetCompanyById(id).Returns(company);
var sut = new CompaniesController(repository);
// act
var actual = sut.Details(id);
// assert
Assert.IsInstanceOfType(actual, typeof(ViewResult));
var viewResult = (ViewResult)actual;
Assert.AreEqual(company, viewResult.Model);
}