Mocking a method that returns a method call to another object

Viewed 220

I'm currently unit testing my code and I have problem with creating a mock using Moq. I'm unit testing Foo, and I wish to mock User.GetSomething() to isolate the test. I have created a qick sample of the code that I wish to test:

public class User(){
    public List<int> GetSomething(){
         return bar.CreateList();
     }
}


public class Foo(User user){
   public int SomeMethod() {
      var x = User.GetSomething()
      Do something with x
      ...
    }
}

I have tried creating a mock by doing the following. I have excluded the assert and unnecessary arrange for this question:

var mock = new Mock<User>();
List<int> someList = new List<int>(){1, 2, 3};
mock.Setup(u => u.CreateList()).Returns(SomeList);

Foo(mock.object)
var res = Foo.SomeMethod();
etc.

But I get the exception: System.NotSupportedException : Unsupported expression: u => u.CreateList()

Non-overridable members (here: User.CreateList) may not be used in setup / verification expressions.

2 Answers

The issue is that, as it says; CreateList is not overrideable, it's not marked virtual and, the input is a concrete (User), and not an interface (IUser).

So to fix this you have 2 options:

  1. Create an IUser interface and use this in your code.
  2. Mark the targeted User methods as virtual

You cannot mock not an overridable methods. In your case, you can change GetSomething() to following: public virtual List<int> GetSomething()

Related