-1

I am writing Unit tests for controller class using XUNIT. Here is my code.

private Mock<StudentService> _StudentService;
private StudentController StudentController;

[Fact]
public void GetStudentsBySubject_ShoutReturnNotNull()
{
    List<StudentViewModel> Students = new List<StudentViewModel>();
 _studentService = new Mock<StudentService>();
    string Subject = "Math";
    _StudentService.Setup(x => x.GetStudentsBySubject(Subject))
      .Returns((Students));

    var controller = new StudentController(_StudentService.Object);

    var result = controller.GetStudentsBySubject(Subject);

    Assert.IsType<List<StudentViewModel>>(result);            
}

It throws error at line.

_StudentService.Setup(x => x.GetCheapestStudentsBySubject(Subject))
      .Returns((Students));

Message: System.NullReferenceException : Object reference not set to an instance of an object

I tried many changes. But nothing worked. What could I be doing wrong here.

The following error appears after fixing the nullreference error:

System.NotSupportedException : Unsupported expression: x => x.GetStudentsBySubject(StudentControllerTests.<>c__DisplayClass2_0.Subject) Non-overridable members (here: StudentService.GetStudentsBySubject) may not be used in setup / verification expressions

Alex
  • 7,343
  • 1
  • 38
  • 52
Techie
  • 73
  • 6

1 Answers1

0

Your variable private Mock<StudentService> _StudentService; has not been initialized and is still null.

You need to assign it a value first:

_StudentService = new Mock<StudentService>();

Edit: Your follow-up error means that you need to mark the method GetStudentsBySubjectas virtual. Otherwise, Moq can't control the behavior of the method.

Alex
  • 7,343
  • 1
  • 38
  • 52
  • I added but still gives error. Sorry that my code had some typing errors. I have corrected them. It gives the following errors.System.NotSupportedException : Unsupported expression: x => x.GetStudentsBySubject(StudentControllerTests.<>c__DisplayClass2_0.Subject) Non-overridable members (here: StudentService.GetStudentsBySubject) may not be used in setup / verification expressions. – Techie Sep 19 '19 at 06:05
  • @Techie see my follow up. add the `virtual` keyword to the GetStudentsBySubject method. – Alex Sep 19 '19 at 06:26
  • Can I fix it without changing the source method. – Techie Sep 19 '19 at 12:06
  • If you don't want to change the source method, you have to create an interface on StudentService and then mock the interface. Otherwise, no - the method has to be virtual. – Alex Sep 19 '19 at 12:17