My problem is that I want to stub a property in my abstract class, because my class in test uses that property. I'm currently using latest version of Moq.
My abstract class looks like this:
public abstract class BaseService
{
protected IDrawingSystemUow Uow { get; set; }
}
And my class in test looks like this:
public class UserService : BaseService, IUserService
{
public bool UserExists(Model model)
{
var user = this.Uow.Users.Find(model.Id);
if(user == null) { return false; }
reurn true;
}
}
I can't figure out how I can stub the Uow
property. Does anybody have any clue? Or is my design that bad that I need to move to Uow
property to my class in test?
Your current setup won't work for one simple reason - Uow
property is non-overridable and Moq's job is done at this point. Cannot override, cannot mock .
Easiest solution is to simply make that property overridable. Change your base class definition to:
public abstract class BaseService
{
protected virtual IDrawingSystemUow Uow { get; set; }
}
Now you can use Moq's protected feature (this requires you to include using Moq.Protected
namespace in your test class):
// at the top of the file
using Moq.Protected;
// ...
var drawingSystemStub = new Mock<IDrawingSystemUow>();
var testedClass = new Mock<UserService>();
testedClass
.Protected()
.Setup<IDrawingSystemUow>("Uow")
.Returns(drawingSystemStub.Object);
// setup drawingSystemStub as any other stub
// exercise test
var result = testedClass.Object.UserExists(...);
I think in your case it's pretty straightforward. You just don't mock the Uow
property but the IDrawingSystemUow
service. So you can create a mock of IDrawingSystemUow
, assign it to the instance of UserService
via the Uow
property and then run the tests (eg of the UserExists
method).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.