Reputation: 47
I'm hung up when specifying mock data to be returned from a mocked repository. My test method:
[TestMethod]
public void GetAllImports_SomeImportRecordsExist_ReturnsNonEmptyList() {
// Arrange
var repo = new Mock<IImportRepository>();
repo.Setup(import => import.GetAll()).Returns(new[] {new Import()});
var manager = new ImportConfigurationManager(repo.Object);
// Act
var result = manager.GetAllImports();
// Assert
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof (IList<Import>));
Assert.IsTrue(result.Any());
}
The last assert fails as the manager under test returns an empty list. The manager:
public class ImportConfigurationManager : IImportConfigurationManager
{
private readonly IImportRepository _importRepository;
public ImportConfigurationManager(IImportRepository repository)
{
_importRepository = repository;
}
public IList<Import> GetAllImports() {
return _importRepository.GetAll(import => import) ?? new Import[0];
}
}
I have stepped through the test and watched the manager call to GetAll return null, so I believe that my error lies in setting up the mock repository instance. Any help would be much appreciated.
Update
Patrick pointed out that I was calling GetAll differently in my manager and test. Making the calls consistent (in either direction) solves the issue. Thanks.
Upvotes: 0
Views: 4170
Reputation: 6992
Below might help. I get a list of imports. Return a List in your setup and make sure the Func has setup correctly.
public class ImportConfigurationManager : IImportConfigurationManager
{
private readonly IImportRepository _importRepository;
public ImportConfigurationManager(IImportRepository repository)
{
_importRepository = repository;
}
public IList<Import> GetAllImports()
{
var imports = _importRepository.GetAll(import => import) ?? new Import[0];
return imports;
}
}
public interface IImportRepository
{
IList<Import> GetAll(Func<object, object> func);
}
public interface IImportConfigurationManager
{
}
[TestMethod]
public void GetAllImports_SomeImportRecordsExist_ReturnsNonEmptyList()
{
// Arrange
var repo = new Mock<IImportRepository>();
repo.Setup(import => import.GetAll(It.IsAny<Func<object, object>>())).Returns(new List<Import>(){new Import()});
var manager = new ImportConfigurationManager(repo.Object);
// Act
var result = manager.GetAllImports();
// Assert
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(IList<Import>));
Assert.IsTrue(result.Any());
}
Upvotes: 1