How to assign values to properties in moq?












47















I have a class with a method that returns an object of type User



public class CustomMembershipProvider : MembershipProvider
{
public virtual User GetUser(string username, string password, string email, bool isApproved)
{
return new User()
{
Name = username
,Password = EncodePassword(password)
,Email = email
,Status = (isApproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente)
// ...
};
}

// ..
}


User is a domain object. Note the Id property with setter as protected:



public class User : IAuditable, IUser
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual UsuarioStatusEnum Status { get; set; }
public virtual string Password { get; set; }
}


Id is protected because it is generated by the database.



Test project



In my Test project I have a Fake repository with a method Store to save/update the object:



public void Store(T obj)
{
if (obj.Id > 0)
_context[obj.Id] = obj;
else
{
var generateId = _context.Values.Any() ? _context.Values.Max(p => p.Id) + 1 : 1;
var stubUser = Mock.Get<T>(obj); // In test, will always mock
stubUser.Setup(s => s.Id).Returns(generateId);
_context.Add(generateId, stubUser.Object);
}
}


In CustomMembershipProvider I have public override MembershipUser CreateUser method that calls the GetUser to create a User.

This way, all I have to do is mock the GetUser method so that the repository can generate the Id



var membershipMoq = new Mock<CustomMembershipProvider>();
membershipMoq.CallBase = true;
membershipMoq
.Setup(p => p.GetUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns<string, string, string, bool>( (username, password, email, isAproved) => {
var moqUser = new Mock<User>();
moqUser.Object.Name = username;
moqUser.Object.Password = password;
moqUser.Object.Email = email;
moqUser.Object.Status = (isAproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente);
return moqUser.Object;
});
_membershipProvider = membershipMoq.Object;


Problem



In theory everything is correct. When CreateUser call 'GetUser' to create a user, the user will return Mock filled;



[TestMethod]
public void CreateUser_deve_criar_usuario_no_repositorio()
{
// Act
MembershipCreateStatus status;
var usr = _membershipProvider.CreateUser(
_fixture.Create<string>(),
_fixture.Create<string>(),
_fixture.Create<string>(),
null, null, true, null,
out status);

// usr should have name, email password filled. But not!

// Assert
status.Should().Be(MembershipCreateStatus.Success);
}


The problem is that Email, Name, Password are empty (with default values)!



enter image description here










share|improve this question

























  • Which class you are testing here? I see only mocks around

    – Sergey Berezovskiy
    May 29 '13 at 14:31






  • 1





    I'm testing my CustomMembershipProvider. status.Should().Be(MembershipCreateStatus.Success); In the repository, the user created with e-mail, name and password empty.

    – ridermansb
    May 29 '13 at 14:35











  • CustomMembershipProvider is a mock in your code. You are testing moq framework?

    – Sergey Berezovskiy
    May 29 '13 at 14:37













  • what is _fixture?

    – levelnis
    May 29 '13 at 15:21











  • @SergeyBerezovskiy CustomMembershipProvider is a mock because he mocks one method on this class, but nevertheless calls the base implementation for every other method (because of .CallBase = true)

    – bvgheluwe
    Sep 5 '16 at 11:17
















47















I have a class with a method that returns an object of type User



public class CustomMembershipProvider : MembershipProvider
{
public virtual User GetUser(string username, string password, string email, bool isApproved)
{
return new User()
{
Name = username
,Password = EncodePassword(password)
,Email = email
,Status = (isApproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente)
// ...
};
}

// ..
}


User is a domain object. Note the Id property with setter as protected:



public class User : IAuditable, IUser
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual UsuarioStatusEnum Status { get; set; }
public virtual string Password { get; set; }
}


Id is protected because it is generated by the database.



Test project



In my Test project I have a Fake repository with a method Store to save/update the object:



public void Store(T obj)
{
if (obj.Id > 0)
_context[obj.Id] = obj;
else
{
var generateId = _context.Values.Any() ? _context.Values.Max(p => p.Id) + 1 : 1;
var stubUser = Mock.Get<T>(obj); // In test, will always mock
stubUser.Setup(s => s.Id).Returns(generateId);
_context.Add(generateId, stubUser.Object);
}
}


In CustomMembershipProvider I have public override MembershipUser CreateUser method that calls the GetUser to create a User.

This way, all I have to do is mock the GetUser method so that the repository can generate the Id



var membershipMoq = new Mock<CustomMembershipProvider>();
membershipMoq.CallBase = true;
membershipMoq
.Setup(p => p.GetUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns<string, string, string, bool>( (username, password, email, isAproved) => {
var moqUser = new Mock<User>();
moqUser.Object.Name = username;
moqUser.Object.Password = password;
moqUser.Object.Email = email;
moqUser.Object.Status = (isAproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente);
return moqUser.Object;
});
_membershipProvider = membershipMoq.Object;


Problem



In theory everything is correct. When CreateUser call 'GetUser' to create a user, the user will return Mock filled;



[TestMethod]
public void CreateUser_deve_criar_usuario_no_repositorio()
{
// Act
MembershipCreateStatus status;
var usr = _membershipProvider.CreateUser(
_fixture.Create<string>(),
_fixture.Create<string>(),
_fixture.Create<string>(),
null, null, true, null,
out status);

// usr should have name, email password filled. But not!

// Assert
status.Should().Be(MembershipCreateStatus.Success);
}


The problem is that Email, Name, Password are empty (with default values)!



enter image description here










share|improve this question

























  • Which class you are testing here? I see only mocks around

    – Sergey Berezovskiy
    May 29 '13 at 14:31






  • 1





    I'm testing my CustomMembershipProvider. status.Should().Be(MembershipCreateStatus.Success); In the repository, the user created with e-mail, name and password empty.

    – ridermansb
    May 29 '13 at 14:35











  • CustomMembershipProvider is a mock in your code. You are testing moq framework?

    – Sergey Berezovskiy
    May 29 '13 at 14:37













  • what is _fixture?

    – levelnis
    May 29 '13 at 15:21











  • @SergeyBerezovskiy CustomMembershipProvider is a mock because he mocks one method on this class, but nevertheless calls the base implementation for every other method (because of .CallBase = true)

    – bvgheluwe
    Sep 5 '16 at 11:17














47












47








47


9






I have a class with a method that returns an object of type User



public class CustomMembershipProvider : MembershipProvider
{
public virtual User GetUser(string username, string password, string email, bool isApproved)
{
return new User()
{
Name = username
,Password = EncodePassword(password)
,Email = email
,Status = (isApproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente)
// ...
};
}

// ..
}


User is a domain object. Note the Id property with setter as protected:



public class User : IAuditable, IUser
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual UsuarioStatusEnum Status { get; set; }
public virtual string Password { get; set; }
}


Id is protected because it is generated by the database.



Test project



In my Test project I have a Fake repository with a method Store to save/update the object:



public void Store(T obj)
{
if (obj.Id > 0)
_context[obj.Id] = obj;
else
{
var generateId = _context.Values.Any() ? _context.Values.Max(p => p.Id) + 1 : 1;
var stubUser = Mock.Get<T>(obj); // In test, will always mock
stubUser.Setup(s => s.Id).Returns(generateId);
_context.Add(generateId, stubUser.Object);
}
}


In CustomMembershipProvider I have public override MembershipUser CreateUser method that calls the GetUser to create a User.

This way, all I have to do is mock the GetUser method so that the repository can generate the Id



var membershipMoq = new Mock<CustomMembershipProvider>();
membershipMoq.CallBase = true;
membershipMoq
.Setup(p => p.GetUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns<string, string, string, bool>( (username, password, email, isAproved) => {
var moqUser = new Mock<User>();
moqUser.Object.Name = username;
moqUser.Object.Password = password;
moqUser.Object.Email = email;
moqUser.Object.Status = (isAproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente);
return moqUser.Object;
});
_membershipProvider = membershipMoq.Object;


Problem



In theory everything is correct. When CreateUser call 'GetUser' to create a user, the user will return Mock filled;



[TestMethod]
public void CreateUser_deve_criar_usuario_no_repositorio()
{
// Act
MembershipCreateStatus status;
var usr = _membershipProvider.CreateUser(
_fixture.Create<string>(),
_fixture.Create<string>(),
_fixture.Create<string>(),
null, null, true, null,
out status);

// usr should have name, email password filled. But not!

// Assert
status.Should().Be(MembershipCreateStatus.Success);
}


The problem is that Email, Name, Password are empty (with default values)!



enter image description here










share|improve this question
















I have a class with a method that returns an object of type User



public class CustomMembershipProvider : MembershipProvider
{
public virtual User GetUser(string username, string password, string email, bool isApproved)
{
return new User()
{
Name = username
,Password = EncodePassword(password)
,Email = email
,Status = (isApproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente)
// ...
};
}

// ..
}


User is a domain object. Note the Id property with setter as protected:



public class User : IAuditable, IUser
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual UsuarioStatusEnum Status { get; set; }
public virtual string Password { get; set; }
}


Id is protected because it is generated by the database.



Test project



In my Test project I have a Fake repository with a method Store to save/update the object:



public void Store(T obj)
{
if (obj.Id > 0)
_context[obj.Id] = obj;
else
{
var generateId = _context.Values.Any() ? _context.Values.Max(p => p.Id) + 1 : 1;
var stubUser = Mock.Get<T>(obj); // In test, will always mock
stubUser.Setup(s => s.Id).Returns(generateId);
_context.Add(generateId, stubUser.Object);
}
}


In CustomMembershipProvider I have public override MembershipUser CreateUser method that calls the GetUser to create a User.

This way, all I have to do is mock the GetUser method so that the repository can generate the Id



var membershipMoq = new Mock<CustomMembershipProvider>();
membershipMoq.CallBase = true;
membershipMoq
.Setup(p => p.GetUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Returns<string, string, string, bool>( (username, password, email, isAproved) => {
var moqUser = new Mock<User>();
moqUser.Object.Name = username;
moqUser.Object.Password = password;
moqUser.Object.Email = email;
moqUser.Object.Status = (isAproved ? UsuarioStatusEnum.Ativo : UsuarioStatusEnum.ConfirmacaoPendente);
return moqUser.Object;
});
_membershipProvider = membershipMoq.Object;


Problem



In theory everything is correct. When CreateUser call 'GetUser' to create a user, the user will return Mock filled;



[TestMethod]
public void CreateUser_deve_criar_usuario_no_repositorio()
{
// Act
MembershipCreateStatus status;
var usr = _membershipProvider.CreateUser(
_fixture.Create<string>(),
_fixture.Create<string>(),
_fixture.Create<string>(),
null, null, true, null,
out status);

// usr should have name, email password filled. But not!

// Assert
status.Should().Be(MembershipCreateStatus.Success);
}


The problem is that Email, Name, Password are empty (with default values)!



enter image description here







c# unit-testing mocking moq






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 '14 at 14:24









Community

11




11










asked May 29 '13 at 14:25









ridermansbridermansb

3,9691592177




3,9691592177













  • Which class you are testing here? I see only mocks around

    – Sergey Berezovskiy
    May 29 '13 at 14:31






  • 1





    I'm testing my CustomMembershipProvider. status.Should().Be(MembershipCreateStatus.Success); In the repository, the user created with e-mail, name and password empty.

    – ridermansb
    May 29 '13 at 14:35











  • CustomMembershipProvider is a mock in your code. You are testing moq framework?

    – Sergey Berezovskiy
    May 29 '13 at 14:37













  • what is _fixture?

    – levelnis
    May 29 '13 at 15:21











  • @SergeyBerezovskiy CustomMembershipProvider is a mock because he mocks one method on this class, but nevertheless calls the base implementation for every other method (because of .CallBase = true)

    – bvgheluwe
    Sep 5 '16 at 11:17



















  • Which class you are testing here? I see only mocks around

    – Sergey Berezovskiy
    May 29 '13 at 14:31






  • 1





    I'm testing my CustomMembershipProvider. status.Should().Be(MembershipCreateStatus.Success); In the repository, the user created with e-mail, name and password empty.

    – ridermansb
    May 29 '13 at 14:35











  • CustomMembershipProvider is a mock in your code. You are testing moq framework?

    – Sergey Berezovskiy
    May 29 '13 at 14:37













  • what is _fixture?

    – levelnis
    May 29 '13 at 15:21











  • @SergeyBerezovskiy CustomMembershipProvider is a mock because he mocks one method on this class, but nevertheless calls the base implementation for every other method (because of .CallBase = true)

    – bvgheluwe
    Sep 5 '16 at 11:17

















Which class you are testing here? I see only mocks around

– Sergey Berezovskiy
May 29 '13 at 14:31





Which class you are testing here? I see only mocks around

– Sergey Berezovskiy
May 29 '13 at 14:31




1




1





I'm testing my CustomMembershipProvider. status.Should().Be(MembershipCreateStatus.Success); In the repository, the user created with e-mail, name and password empty.

– ridermansb
May 29 '13 at 14:35





I'm testing my CustomMembershipProvider. status.Should().Be(MembershipCreateStatus.Success); In the repository, the user created with e-mail, name and password empty.

– ridermansb
May 29 '13 at 14:35













CustomMembershipProvider is a mock in your code. You are testing moq framework?

– Sergey Berezovskiy
May 29 '13 at 14:37







CustomMembershipProvider is a mock in your code. You are testing moq framework?

– Sergey Berezovskiy
May 29 '13 at 14:37















what is _fixture?

– levelnis
May 29 '13 at 15:21





what is _fixture?

– levelnis
May 29 '13 at 15:21













@SergeyBerezovskiy CustomMembershipProvider is a mock because he mocks one method on this class, but nevertheless calls the base implementation for every other method (because of .CallBase = true)

– bvgheluwe
Sep 5 '16 at 11:17





@SergeyBerezovskiy CustomMembershipProvider is a mock because he mocks one method on this class, but nevertheless calls the base implementation for every other method (because of .CallBase = true)

– bvgheluwe
Sep 5 '16 at 11:17












2 Answers
2






active

oldest

votes


















94














The way you prepare the mocked user is the problem.



moqUser.Object.Name = username;


will not set the name, unless you have setup the mock properly.
Try this before assigning values to properties:



moqUser.SetupAllProperties();


This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).



You can also use SetProperty() method to setup individual properties to be able to record the passed in value.



Another approach is:



var mockUser = Mock.Of<User>( m =>
m.Name == "wahtever" &&
m.Email == "some@example.com");

return mockUser;





share|improve this answer





















  • 4





    You can use SetupProperty to do it one at a time, also

    – Justin Pihony
    May 29 '13 at 15:59











  • Thanks, I'll extend the answer

    – Sunny Milenov
    May 29 '13 at 16:01



















6














I think you are missing purpose of mocking. Mocks used to mock dependencies of class you are testing:



enter image description here



System under test (SUT) should be tested in isolation (i.e. separate from other units). Otherwise errors in dependencies will cause your SUTs tests to fail. Also you should not write tests for mocks. That gives you nothing, because mocks are not production code. Mocks are not executed in your application.



So, you should mock CustomMembershipProvider only if you are testing some unit, which depends on it (BTW it's better to create some abstraction like interface ICustomMembershipProvider to depend on).



Or, if you are writing tests for CustomMembershipProvider class, then it should not be mocked - only dependencies of this provider should be mocked.






share|improve this answer
























  • In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

    – Sunny Milenov
    May 29 '13 at 15:47











  • @SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

    – Sergey Berezovskiy
    May 29 '13 at 17:01






  • 1





    @lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

    – ridermansb
    May 29 '13 at 17:31











  • .. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

    – ridermansb
    May 29 '13 at 17:33






  • 2





    @lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

    – Sunny Milenov
    May 29 '13 at 18:19













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16816551%2fhow-to-assign-values-to-properties-in-moq%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









94














The way you prepare the mocked user is the problem.



moqUser.Object.Name = username;


will not set the name, unless you have setup the mock properly.
Try this before assigning values to properties:



moqUser.SetupAllProperties();


This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).



You can also use SetProperty() method to setup individual properties to be able to record the passed in value.



Another approach is:



var mockUser = Mock.Of<User>( m =>
m.Name == "wahtever" &&
m.Email == "some@example.com");

return mockUser;





share|improve this answer





















  • 4





    You can use SetupProperty to do it one at a time, also

    – Justin Pihony
    May 29 '13 at 15:59











  • Thanks, I'll extend the answer

    – Sunny Milenov
    May 29 '13 at 16:01
















94














The way you prepare the mocked user is the problem.



moqUser.Object.Name = username;


will not set the name, unless you have setup the mock properly.
Try this before assigning values to properties:



moqUser.SetupAllProperties();


This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).



You can also use SetProperty() method to setup individual properties to be able to record the passed in value.



Another approach is:



var mockUser = Mock.Of<User>( m =>
m.Name == "wahtever" &&
m.Email == "some@example.com");

return mockUser;





share|improve this answer





















  • 4





    You can use SetupProperty to do it one at a time, also

    – Justin Pihony
    May 29 '13 at 15:59











  • Thanks, I'll extend the answer

    – Sunny Milenov
    May 29 '13 at 16:01














94












94








94







The way you prepare the mocked user is the problem.



moqUser.Object.Name = username;


will not set the name, unless you have setup the mock properly.
Try this before assigning values to properties:



moqUser.SetupAllProperties();


This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).



You can also use SetProperty() method to setup individual properties to be able to record the passed in value.



Another approach is:



var mockUser = Mock.Of<User>( m =>
m.Name == "wahtever" &&
m.Email == "some@example.com");

return mockUser;





share|improve this answer















The way you prepare the mocked user is the problem.



moqUser.Object.Name = username;


will not set the name, unless you have setup the mock properly.
Try this before assigning values to properties:



moqUser.SetupAllProperties();


This method will prepare all properties on the mock to be able to record the assigned value, and replay it later (i.e. to act as real property).



You can also use SetProperty() method to setup individual properties to be able to record the passed in value.



Another approach is:



var mockUser = Mock.Of<User>( m =>
m.Name == "wahtever" &&
m.Email == "some@example.com");

return mockUser;






share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 26 '14 at 17:38









Jones

9831431




9831431










answered May 29 '13 at 15:45









Sunny MilenovSunny Milenov

17.3k46696




17.3k46696








  • 4





    You can use SetupProperty to do it one at a time, also

    – Justin Pihony
    May 29 '13 at 15:59











  • Thanks, I'll extend the answer

    – Sunny Milenov
    May 29 '13 at 16:01














  • 4





    You can use SetupProperty to do it one at a time, also

    – Justin Pihony
    May 29 '13 at 15:59











  • Thanks, I'll extend the answer

    – Sunny Milenov
    May 29 '13 at 16:01








4




4





You can use SetupProperty to do it one at a time, also

– Justin Pihony
May 29 '13 at 15:59





You can use SetupProperty to do it one at a time, also

– Justin Pihony
May 29 '13 at 15:59













Thanks, I'll extend the answer

– Sunny Milenov
May 29 '13 at 16:01





Thanks, I'll extend the answer

– Sunny Milenov
May 29 '13 at 16:01













6














I think you are missing purpose of mocking. Mocks used to mock dependencies of class you are testing:



enter image description here



System under test (SUT) should be tested in isolation (i.e. separate from other units). Otherwise errors in dependencies will cause your SUTs tests to fail. Also you should not write tests for mocks. That gives you nothing, because mocks are not production code. Mocks are not executed in your application.



So, you should mock CustomMembershipProvider only if you are testing some unit, which depends on it (BTW it's better to create some abstraction like interface ICustomMembershipProvider to depend on).



Or, if you are writing tests for CustomMembershipProvider class, then it should not be mocked - only dependencies of this provider should be mocked.






share|improve this answer
























  • In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

    – Sunny Milenov
    May 29 '13 at 15:47











  • @SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

    – Sergey Berezovskiy
    May 29 '13 at 17:01






  • 1





    @lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

    – ridermansb
    May 29 '13 at 17:31











  • .. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

    – ridermansb
    May 29 '13 at 17:33






  • 2





    @lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

    – Sunny Milenov
    May 29 '13 at 18:19


















6














I think you are missing purpose of mocking. Mocks used to mock dependencies of class you are testing:



enter image description here



System under test (SUT) should be tested in isolation (i.e. separate from other units). Otherwise errors in dependencies will cause your SUTs tests to fail. Also you should not write tests for mocks. That gives you nothing, because mocks are not production code. Mocks are not executed in your application.



So, you should mock CustomMembershipProvider only if you are testing some unit, which depends on it (BTW it's better to create some abstraction like interface ICustomMembershipProvider to depend on).



Or, if you are writing tests for CustomMembershipProvider class, then it should not be mocked - only dependencies of this provider should be mocked.






share|improve this answer
























  • In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

    – Sunny Milenov
    May 29 '13 at 15:47











  • @SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

    – Sergey Berezovskiy
    May 29 '13 at 17:01






  • 1





    @lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

    – ridermansb
    May 29 '13 at 17:31











  • .. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

    – ridermansb
    May 29 '13 at 17:33






  • 2





    @lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

    – Sunny Milenov
    May 29 '13 at 18:19
















6












6








6







I think you are missing purpose of mocking. Mocks used to mock dependencies of class you are testing:



enter image description here



System under test (SUT) should be tested in isolation (i.e. separate from other units). Otherwise errors in dependencies will cause your SUTs tests to fail. Also you should not write tests for mocks. That gives you nothing, because mocks are not production code. Mocks are not executed in your application.



So, you should mock CustomMembershipProvider only if you are testing some unit, which depends on it (BTW it's better to create some abstraction like interface ICustomMembershipProvider to depend on).



Or, if you are writing tests for CustomMembershipProvider class, then it should not be mocked - only dependencies of this provider should be mocked.






share|improve this answer













I think you are missing purpose of mocking. Mocks used to mock dependencies of class you are testing:



enter image description here



System under test (SUT) should be tested in isolation (i.e. separate from other units). Otherwise errors in dependencies will cause your SUTs tests to fail. Also you should not write tests for mocks. That gives you nothing, because mocks are not production code. Mocks are not executed in your application.



So, you should mock CustomMembershipProvider only if you are testing some unit, which depends on it (BTW it's better to create some abstraction like interface ICustomMembershipProvider to depend on).



Or, if you are writing tests for CustomMembershipProvider class, then it should not be mocked - only dependencies of this provider should be mocked.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 29 '13 at 15:42









Sergey BerezovskiySergey Berezovskiy

188k23319366




188k23319366













  • In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

    – Sunny Milenov
    May 29 '13 at 15:47











  • @SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

    – Sergey Berezovskiy
    May 29 '13 at 17:01






  • 1





    @lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

    – ridermansb
    May 29 '13 at 17:31











  • .. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

    – ridermansb
    May 29 '13 at 17:33






  • 2





    @lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

    – Sunny Milenov
    May 29 '13 at 18:19





















  • In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

    – Sunny Milenov
    May 29 '13 at 15:47











  • @SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

    – Sergey Berezovskiy
    May 29 '13 at 17:01






  • 1





    @lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

    – ridermansb
    May 29 '13 at 17:31











  • .. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

    – ridermansb
    May 29 '13 at 17:33






  • 2





    @lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

    – Sunny Milenov
    May 29 '13 at 18:19



















In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

– Sunny Milenov
May 29 '13 at 15:47





In theory, you are right. Unless the method under test calls another virtual method on the same class, where CallBase = true comes into play. I agree this is bad design to start with, but sometimes people work with legacy code, etc.

– Sunny Milenov
May 29 '13 at 15:47













@SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

– Sergey Berezovskiy
May 29 '13 at 17:01





@SunnyMilenov sorry, but in practice I never test mocks. Is there any examples when testing mock can be useful?

– Sergey Berezovskiy
May 29 '13 at 17:01




1




1





@lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

– ridermansb
May 29 '13 at 17:31





@lazyberezovsky excellent explanation. And I agree with you. In this particular case I test CustomMembershipProvider, specifically the creation of users: CreateUser method ..

– ridermansb
May 29 '13 at 17:31













.. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

– ridermansb
May 29 '13 at 17:33





.. Inside the CreateUser method, an object User is created call GetUser method. But the Id property of my User object a setter is as protected (Id is generated by the database)...

– ridermansb
May 29 '13 at 17:33




2




2





@lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

– Sunny Milenov
May 29 '13 at 18:19







@lzayberezovsky: in this concrete example he is not testing the mock, but CustomMembershipProviderClass. He just uses moq as a helper to let him override one particular method of it, instead of creating an inherited class, and override there. In this case, this is not a mock, but stub.

– Sunny Milenov
May 29 '13 at 18:19




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16816551%2fhow-to-assign-values-to-properties-in-moq%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine