1

I have the following code:

 var service = new Mock<INavigationService>(); service.Setup(x => x.GetSchemes(new SchemeFilterEntity())).Returns(new List<SchemeEntity> { new SchemeEntity { Id = 1, Name = "Test" }, new SchemeEntity { Id = 2, Name = "Test 2" } }); var sut = service.Object; var sut = service.GetSchemes(new SchemeFilterEntity()); 

However when the GetSchemes method is called it returns null?

Any ideas?

2 Answers 2

3

I believe that should be

service.Setup(x => x.GetSchemes(It.IsAny< SchemeFilterEntity >())).Returns.....

because otherwise, moq will be looking for that exact instance of the 'new SchemeFilterEntity()' that you passed in in the setup method, which will never match anything else.

Edit: That said, your sut should not be the thing you are mocking, it should be the thing that's using your mocked object.

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

1 Comment

yeah - sorry - the last 2 lines are only there to show that trying to call GetSchemes does not return the expected stuff..
0

I don't know what you are tring to test but if you want "Override" the behavior of GetSchema using a mocked object that method must be virtual on the class

If you want to use the mocked object to stub out the INavigationService you have to do the below

 ......... var sut = service.Object; SomeThing.UseNavigavtionService(sut); //this is supposed to be the class which you will test.Sut is a mocked INavigationService 

in your setup you should also use It.IsAny< SchemeFilterEntity >() instead of create a concrete object

1 Comment

I don't want GetSchemes to actually do it's work, I thought the point was to be able to fake the results of the GetSchemes call so that i can use the service in a test? The last 2 lines are only here for illustration.