我做了重构,如果我们的仓库工厂,使之更加通用的,现在建立资料库的方法看起来像这样:嘲讽通用仓库工厂方法
public TRepository CreateRepository<TRepository>(params object[] parameters)
where TRepository : class
{
if (_serviceProvider == null)
throw new ArgumentNullException(nameof(_serviceProvider));
return ActivatorUtilities.CreateInstance<TRepository>(_serviceProvider, parameters);
}
在我的生产代码,我使用它像这样和它的作品般的魅力:
_concreteRepo = repoFactory.CreateRepository<ConcreteRepo>();
但是,当我试图重构单元测试,以及我遇到困难建立工厂,这是我要做的事,但它不工作。
public class Tests
{
// Since I am using Moq I can't mock anything but abstract types thus having problems with type conversion in set up.
protected readonly Mock<IConcreteRepository> _concreteRepositoryMock = new Mock<IConcreteRepository>();
protected readonly Mock<IRepositoryFactory> _factoryMock = new Mock<IRepositoryFactory>();
[SetUp]
public void SetUp()
{
// If I don't cast concreteRepositoryMock compiler complains that cannot convert from abstract to concrete repository.
// If I cast it fails and returns null.
_factoryMock.Setup(f => f.CreateRepository<ConcreteRepository>())
.Returns(_concreteRepositoryMock.Object as ConcreteRepository);
}
}
任何想法如何解决它?看起来像我的CreateRepository
方法返回具体类型,但嘲笑我不能嘲笑我的具体存储库。我也无法将抽象类型传递到CreateRepository
,因为CreateInstance
需要具体类型。
不直接相关,但在前5行代码中存在Factory,存储库,通用性,参数数组和ServiceProvider可能是过度工程的标志。 – guillaume31