Question

I know some ASP MVC, trying to embrace TDD. Following examples here installed xUnit and TestDriven (which includes Moq).

Problem is that I was trying to Mock an image upload viewmodel so I can assert it is being uploaded.

Moq gave me problem:

Invalid setup on a non-virtual (overridable in VB) member

while trying to

var imageMock = new Mock<ImageViewModel>();
imageMock.Setup(x => x.IsUrl).Returns(true);`

I am not sure how to keep on going - its nonsense to create interfaces for a view model, I am programming for site, not for testing environment.

Should I replace Mock environment or define interface or ... ?

Please give some experienced and informative advise and please provide or at least like to good samples to what you're advising me to do.

Thanks!

Was it helpful?

Solution

First of all, is this a auto property?

public bool IsUrl {get; set;}

If so, just set the value yourself in the set up of your test. If it's not an auto property, does it make more sense to move it into a method, instead of property. And at that time, you could make the method virtual (which is what the error message is actually saying.)

When mocking, you can't mock things that are either not interfaces or are not virtual (I believe there are some paid mocking libraries that let you, but FakeItEasy, Moq and others require that it be virtual.)

To do this, you would simply need to make the property look like this:

public virtual bool IsUrl {get; set;}

Secondly, what are you testing on your view model? Testing getters and setters is largely a waste of time because they will most likely be tested in other places of your code. Plus, tests on getters and setters are testing the compiler, not your code. If getters and setters don't work in .NET you've got a whole host of problems. It would be better to test the creation of your view model and then make sure that it has the right values after creation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top