-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

2
  • Did you initialize "_StudentService" before use? (e.g. "_StudentService = new Mock<StudentService>()") Commented Sep 19, 2019 at 5:11
  • Regarding second problem: stackoverflow.com/questions/40828489/… Commented Sep 19, 2019 at 6:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 see my follow up. add the virtual keyword to the GetStudentsBySubject method.
Can I fix it without changing the source method.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.