I have successfully created a mocked Person
object and I am now trying to use my AddChild()
method to add a child to the object via its' Id. My test looks like this:
public class PersonManagerMockTest
{
private static Guid personGuid;
[ClassInitialize]
public static void Init(TestContext test)
{
personGuid = Guid.NewGuid();
}
[TestMethod]
public void AddNewPerson()
{
//Arrange
var mockDbSet = new Mock<DbSet<Person>>();
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
.Returns<Person>(p => p);
var mockContext = new Mock<IHiveTiesContext>();
mockContext.Setup(x => x.People)
.Returns(mockDbSet.Object);
var manager = new Manager(mockContext.Object);
//Assert
var _person = manager.CreatePerson("Winston", "Gabriel", DateTime.Now, 'M', personGuid);
var fatherid = mockDbSet.Object.SingleOrDefault(x => x.RowId == personGuid).Id;
manager.AddChild(new Person
{
FirstName = "Aaron",
LastName = "Gabriel",
DOB = new DateTime(1991, 01, 16),
FavoriteColor = "Red",
FatherId = fatherid,
});
//Act
mockDbSet.Verify(x => x.Add(It.IsAny<Person>()), Times.Once);
mockContext.Verify(x => x.SaveChanges(), Times.Once);
}
}
The mocked Person
object is successfully created, but the problem comes from this statement:
var fatherid = mockDbSet.Object.SingleOrDefault(x => x.RowId == personGuid).Id;
I am not sure how to retrieve the Id
from the mocked Person
object, and as I thought this statement returned 0
for fatherid
meaning that it is null
. This is my first time running mocks, so I am still learning. Any suggestions on how to retrieve the Id
from this mocked Person
object?
I will appreciate all suggestions. Thank you.
I used CreateMockSet
method from this answer.
Change:
var mockDbSet = new Mock<DbSet<Person>>();
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
.Returns<Person>(p => p);
To:
var persons = new List<Person>();
var mockDbSet = CreateMockSet(persons.AsQueryable());
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
.Callback<Person>(persons.Add)
.Returns <Person>(p => p);
The Callback
method populate the persons
list with the new Person
instance.
The CreateMockSet()
create Mock<DbSet<Person>>
with the return setup of persons
(on mockDbSet.Object
)
Making OldFoxes answer more clear for the innate!
mockSet.Setup(x => x.Add(It.IsAny<ValuationCompany>()))
.Callback<ValuationCompany>(data.Add)
.Returns<ValuationCompany>(p =>
{
p.Id = 23; // Assign whatever you want here.
return p;
});