我正在使用 Autofac 实现 Xunit,我可以通过以下代码使其工作:
using (var scoped = DbFixture.Container.Resolve<UserReponsitory>())
{
var result = (scoped.GetAll()).ToList().Count();
Assert.Equal(2, result);
}
但我想注入 UserReponsitory 来测试方法而不是使用DbFixture.Container.Resolve
. 是否可以使下面的代码工作?
单元测试1.cs
namespace XUnitTestPro
{
public class UnitTest1:IClassFixture<DbFixture>
{
private IUserReponsitory _userReponsitory;
public UnitTest1(IUserReponsitory userReponsitory)
{
_userReponsitory = userReponsitory;
}
[Fact]
public void Test1()
{
//using (var scoped = DbFixture.Container.Resolve<UserReponsitory>())
//{
// var result = (scoped.GetAll()).ToList().Count();
// Assert.Equal(2, result);
//}
var result = _userReponsitory.GetAll().ToList().Count();
Assert.Equal(2, result);
}
}
}
DbFixture.cs
namespace XUnitTestPro
{
public class DbFixture
{
public static IContainer Container { get; set; }
public DbFixture()
{
var builder = new ContainerBuilder();
var option = new DbContextOptionsBuilder<UserContext>().UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=EFProject;Trusted_Connection=True;MultipleActiveResultSets=true").Options;
UserContext context = new UserContext(option);
builder.RegisterInstance(context).As<UserContext>();
builder.RegisterType<UserReponsitory>().AsSelf().As<IUserReponsitory>();
builder.RegisterAssemblyTypes(typeof(DbFixture).GetTypeInfo().Assembly);
Container = builder.Build();
}
}
}
目前,我得到以下错误,它似乎与IClassFixture<DbFixture>
并且public UnitTest1(IUserReponsitory userReponsitory)
不同。
消息:以下构造函数参数没有匹配的夹具数据:IUserReponsitory userReponsitory
DbFixture.Container.Resolve
有没有什么方法可以在不调用类似于注入 MVC 控制器的情况下实现以下代码?
public UnitTest1(IUserReponsitory userReponsitory)
{
_userReponsitory = userReponsitory;
}
换句话说,我怎么能依赖注入单元测试类?
任何帮助,将不胜感激。