Reputation: 366
i'm currently working on my testproject to test all of my domain entities in the same way. Therefore, I made a base class, which will be inherited by all of my test classes, to ensure that all of them share the same behavior.
All of my methods work fine, except for the GetByPrimaryKey, which returns null when it should return an instance of my type.
Implementation of the base class:
[TestClass]
public abstract class RepositoryTestBase<E, C>
where E : EntityBase
where C : IDBContext
{
protected E MockedEntity;
protected IRepository<E, C> Repository { get { return _mockedRepository.Object; } }
private Mock<IRepository<E, C>> _mockedRepository;
[TestInitialize]
public void Init()
{
MockedEntity = System.Activator.CreateInstance<E>();
_mockedRepository = new Mock<IRepository<E, C>>();
_mockedRepository.Setup(f => f.Add(MockedEntity)).Callback(() => { MockedEntity.Id = 1; });
_mockedRepository.Setup(f => f.GetByPrimaryKey(MockedEntity.Id)).Returns(MockedEntity);
_mockedRepository.Setup(f => f.Update(MockedEntity)).Callback(() => { MockedEntity.AlteradoEm = DateTime.Now; });
_mockedRepository.Setup(f => f.Remove(MockedEntity)).Callback(() => { MockedEntity.Deleted = true; });
}
}
How can I make the Returns() method return an object instead of returning null? And why is it returning null? Thanks in advance.
Upvotes: 2
Views: 5094
Reputation: 247551
why is it returning null?
The Id
has the potential to change. Using the constant MockedEntity.Id
which would default to 0
at the time of setup would cause the problem you are experiencing because if you were to call the mocked method after having already added it to the repository the Id
would not match and the mocked behavior would not be exercised.
How can I make the Returns() method return an object instead of returning null?
Instead make the Returns()
statement flexible by using It.IsAny<int>()
in the setup and comparing the provided Id
to the current Id
of the entity, only returning the entity if the Ids matches.
_mockedRepository
.Setup(_ => _.GetByPrimaryKey(It.IsAny<int>()))
.Returns((int id) => id == MockedEntity.Id ? MockedEntity : default(E));
Upvotes: 0
Reputation: 1618
Since you only have a single MockedObject, you don't really care about the input parameter into the mock repository setup.
As such, you could do something like:
_mockedRepository.Setup(f => f.GetByPrimaryId(It.IsAny<int>()).Returns(MockedEntity);
where is the type of your entities' key (or whatever "GetByPrimaryId" expects)
Upvotes: 3