I'm trying to unit test my ASP MVC application, but my test fails with the message Message: Assert.AreEqua failed. Expected:<>. Actual: <Error>.
Now, I assume this is because I've set up the test wrong, but I can't find the place where I might have missed something. Any hints would be greatly appreciated. I'm using Moq.
My test class:
[TestClass] public class ErrorControllerTest { [TestMethod] public void TestErrorView() { var repositoryMock = new Mock<IErrorRepository>(); var errors = new List<ErrorModel>(); errors.Add(new ErrorModel() { Id = "id", Message = "message" }); repositoryMock.Setup(r => r.GetErrors()).Returns(errors); var controller = new ErrorController(repositoryMock.Object); var result = (ViewResult) controller.Error(1); Assert.AreEqual(result.ViewName, "Error"); repositoryMock.VerifyAll(); } } For good measure, this is the controller under test:
public class ErrorController : Controller { private readonly IErrorRepository errorRepository; public ErrorController(IErrorRepository errorRepository) { this.errorRepository = errorRepository; } public ActionResult Error(int? page) { var errors = errorRepository.GetErrors(); //// stuff for paging int pageSize = 10; int pageNumber = (page ?? 1); // if there is no page, return page 1 return View(errors.ToPagedList(pageNumber, pageSize)); } } And the repository:
public interface IErrorRepository { List<ErrorModel> GetErrors(); } public class ErrorRepository : IErrorRepository { public ErrorModel Errors { get; set; } public List<ErrorModel> ErrorList { get; set; } public List<ErrorModel> GetErrors() { string cs = "Data Source=" + "some path"; using (SQLiteConnection con = new SQLiteConnection(cs)) { var listOfErrors = new List<ErrorModel>(); string stm = "SELECT * FROM Error"; con.Open(); using (SQLiteCommand cmd = new SQLiteCommand(stm, con)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { listOfErrors.Add(new ErrorModel { Id = rdr["ID"].ToString(), Message = rdr["Message"].ToString() }); } rdr.Close(); ErrorList = listOfErrors; } } con.Close(); } return ErrorList; } }
Assert.AreEqual(result.ViewName, "Error");givesExpected:<>. Actual: <Error>then you have your arguments round the wrong way. Every test environment does it differently (within the 2 options obviously) - check intellisense, but it should probably beAssert.AreEqual("Error", result.ViewName);. Doesn't explain why it's blank though.