I've thoroughly searched stackoverflow for an answer to this question, but with no luck.
I've simplified my test. My issue is that I cannot get the setup of GetEntityFieldsById to work.
So this is my simplified class:
public class EntityClass
{
public Guid Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
And a very simple repository:
public interface IRepository
{
IList<T> GetEntityFieldsById<T>(Guid id, Expression<Func<EntityClass, T>> selector);
}
And a very simple class with the code to be tested:
public class CodeToTest
{
private readonly IRepository _repository;
public CodeToTest(IRepository repository)
{
_repository = repository;
}
public void MethodToTest(Guid id)
{
var result = _repository.GetEntityFieldsById(id, x => new {x.StartDate, x.EndDate});
//...
}
}
Here I try to setup the GetEntityFieldsById method, but can't get it to work:
[TestClass]
public class UnitTest1
{
private Mock<IRepository> _repositoryMock;
private CodeToTest _codeToTest;
[TestInitialize]
public void TestInitialize()
{
_repositoryMock = new Mock<IRepository>(MockBehavior.Strict);
_codeToTest = new CodeToTest(_repositoryMock.Object);
}
[TestMethod]
public void TestMethod1()
{
var fakeId = Guid.NewGuid();
SetupGetEntityFieldsById<object>(fakeId, new List<object>());
_codeToTest.MethodToTest(fakeId);
// assert something
}
private void SetupGetEntityFieldsById<T>(Guid id, IList<T> result)
{
_repositoryMock.Setup(
m => m.GetEntityFieldsById(It.Is<Guid>(p => p == id),
It.IsAny<Expression<Func<EntityClass, T>>>()))
.Returns(result);
}
}
As I'm using MockBehavior.Strict
I get the classic "missing setup" error when running the test:
Test method UnitTestProject1.UnitTest1.TestMethod1 threw exception: Moq.MockException: IRepository.GetEntityFieldsById<<>f__AnonymousType0
2>(d1b3c6fb-5a5e-4f0a-9f68-191ca6a61bff, x => new <>f__AnonymousType0
2(StartDate = x.StartDate, EndDate = x.EndDate)) invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.