[英]How can I unit test my UnitOfWork class with NUnit?
这是我的 UnitOfWork class:
public class UnitOfWork : IUnitOfWork
{
protected SampleProjectDbContext _db { get; private set; }
private IServiceProvider _serviceProvider;
private bool _disposed;
public UnitOfWork(SampleProjectDbContext db, IServiceProvider serviceProvider)
{
_db = db;
_serviceProvider = serviceProvider;
}
// some code
public IStudentRepository StudentRepository => _serviceProvider.GetRequiredService<IStudentRepository>();
public ICourseRepository CourseRepository => _serviceProvider.GetService<ICourseRepository>();
public IRegisteredCourseRepository RegisteredCourseRepository => _serviceProvider.GetService<IRegisteredCourseRepository>();
}
现在如何使用 NUnit 为 StudentRepository 属性编写单元测试? 我找不到测试 StudentRepository 属性的方法。
这是我的 ServiceModuleExtentions class:
public static class ServiceModuleExtentions
{
public static void RegisterInfrastructureServices(this IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<IUnitOfWork, UnitOfWork>();
serviceCollection.AddScoped<ICourseRepository, CourseRepository>();
serviceCollection.AddScoped<IStudentRepository, StudentRepository>();
serviceCollection.AddScoped<IRegisteredCourseRepository, RegisteredCourseRepository>();
}
}
我在我的启动中这样使用它:
public void ConfigureServices(IServiceCollection services)
{
// some code
services.RegisterInfrastructureServices();
}
我像这样测试它,但它给出了错误:
public class UnitOfWork_UnitTest
{
private UnitOfWork _unitOfWork;
private Mock<IServiceProvider> _serviceProviderMock;
private Mock<SampleProjectDbContext> _dbContextMock;
[SetUp]
public void Setup()
{
_serviceProviderMock = new Mock<IServiceProvider>();
_dbContextMock = new Mock<SampleProjectDbContext>();
_unitOfWork = new UnitOfWork(_dbContextMock.Object, _serviceProviderMock.Object);
}
[Test]
public void Should_Return_IStudentRepository()
{
// Arrange
_serviceProviderMock
.Setup(x => x.GetService(typeof(IStudentRepository)))
.Returns(It.IsAny<IStudentRepository>());
// Act
var result = _unitOfWork.StudentRepository;
// Assert
Assert.IsAssignableFrom<IStudentRepository>(result);
}
}
错误是“System.InvalidOperationException:没有注册类型'SampleProject.Core.Contracts.IStudentRepository'的服务。”
将您的Setup
方法更改为:
_serviceProviderMock = new Mock<IServiceProvider>();
_serviceProviderMock
.Setup(x => x.GetService(typeof(IStudentRepository)))
.Returns(new StudentRepository());
_dbContextMock = new Mock<SampleProjectDbContext>();
_unitOfWork = new UnitOfWork(_dbContextMock.Object, _serviceProviderMock.Object);
问题是您当前正在将_serviceProviderMock
注入到_unitOfWork
构造函数中,然后再进行设置。 您还需要提供一个实例而不是匹配器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.