Well this seemed to be trivial before i started this, but i cant get it to work.
This code is the essential elements of the problem.
I have a class with a private variable which i can retrieve the value of by calling a method.
public class CheckItOut {
private bool authenticated = false;
public CheckItOut(){}
public bool IsAuthenticated(){
return authenticated;
}
}
Then i have a testclass which mocks this class, and injects it via constructor into the class which im testing.
.
.
.
Mock<CheckItOut> mockedCheckItOut = new Mock<CheckItOut>();
mockedCheckItOut.Setup(x => x.IsAuthenticated()).Returns(true);
Controller sut = new Controller(mockedCheckItOut);
.
.
.
When i step through the test code and reach the .Setup, i get the following error
System.NotSupportedException: 'Unsupported expression: x => x.IsAuthenticated()
Non-overridable members (here: CheckItOut.IsAuthenticated) may not be used in setup
I don't understand. Im not doing anything to any members of CheckItOut. Im mocking/replacing a method call with my own implementation returning true.
Can anyone see what im doing wrong ?
Thankyou for your time.
CodePudding user response:
The problem here is that you're trying to mock a non virtual member/function of your class. That is something that Moq (or any mocking framework) cannot do. If you want to mock your class you have to define the IsAuthenticated function as virtual.
An even better way to have more control over your objects in tests is to use interfaces for your classes. This way you're able to mock all of the public behaviour of your objects for the tests.