0

I study to write a module test by moq , and this simply test failed with

Message: Test method UnitTests.AdminTests.IndexContainPlayerList threw exception: System.NullReferenceException:

[TestMethod] public void IndexContainPlayerList() { //Arrange Mock<IPlayerRepository> mock = new Mock<IPlayerRepository>(); mock.Setup(m => m.Players).Returns(new List<Player>() { new Player () { Id = 1, Name = "Karye", Surname = "Irving", Team = new Team(){ Id = 1, Name = "Boston Celtics" }, TeamId = 1 }, new Player () { Id = 1, Name = "Stephan", Surname = "Carry", Team = new Team(){ Id = 2, Name = "Golden State Warriors" }, TeamId = 2 } }); AdminController target = new AdminController(mock.Object, null); //Action Player[] resultList = ((IEnumerable<Player>)target.Index().ViewData.Model).ToArray(); //Assert Assert.AreEqual(resultList.Length, 2); } 

method which I am testing

 public ViewResult Index() { ViewBag.ChoosingTeam = new SelectList(teamRepository.Teams, "Name ", "Name"); return View(playerRepository.Players.ToList()); } 

why test run failed, may be i lose something or don't understand?

2
  • In the exception stacktrace, it should give you a hint to what line the NRE is being thrown. Commented Jan 11, 2019 at 8:37
  • ViewBag.ChoosingTeam = ....; but it need to realize? Commented Jan 11, 2019 at 8:38

1 Answer 1

1

A NullReferenceException is being thrown is because you are passing a null into your AdminController that I am assuming is for your ITeamsRepository.

As you can see you are attempting to access the teamRepository, since that is null, a NullReferenceException is being thrown.

You need to also mock out that dependency.
Example:

Mock<ITeamsRepository> teamsMock = new Mock<ITeamsRepository>(); AdminController target = new AdminController(mock.Object, teamsMock.Object); 
Sign up to request clarification or add additional context in comments.

2 Comments

@Andrei Excellent, I would also question the point of that test, it's not really testing anything other than verifying that it's using your IPlayerRepository to get players.
i check, sent Index() method the model <Player> to View, and check those or not those Players are sending to view