我正在尝试在XUnit测试中为AppService实现依赖注入。理想的目标是运行原始应用程序启动/配置,并使用启动中的任何依赖项注入,而不是在测试中再次重新初始化所有DI,这就是整个目标。
更新:Mohsen的答案很接近。需要更新几个语法/要求错误才能起作用。
由于某种原因,原始应用程序可以工作,并且可以致电Department App Service。但是,它无法在Xunit中调用。最终使Testserver在原始应用程序中使用Startup和Configuration进行工作。现在收到以下错误:
Message: The following constructor parameters did not have matching fixture data: IDepartmentAppService departmentAppService
namespace Testing.IntegrationTests
{
public class DepartmentAppServiceTest
{
public DBContext context;
public IDepartmentAppService departmentAppService;
public DepartmentAppServiceTest(IDepartmentAppService departmentAppService)
{
this.departmentAppService = departmentAppService;
}
[Fact]
public async Task Get_DepartmentById_Are_Equal()
{
var options = new DbContextOptionsBuilder<SharedServicesContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
context = new DBContext(options);
TestServer _server = new TestServer(new WebHostBuilder()
.UseContentRoot("C:\\OriginalApplication")
.UseEnvironment("Development")
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath("C:\\OriginalApplication")
.AddJsonFile("appsettings.json")
.Build()).UseStartup<Startup>());
context.Department.Add(new Department { DepartmentId = 2, DepartmentCode = "123", DepartmentName …Run Code Online (Sandbox Code Playgroud) 我有.NET Core 2.0项目,其中包含存储库模式和xUnit测试.
现在,这里有一些代码.
控制器:
public class SchedulesController : Controller
{
private readonly IScheduleRepository repository;
private readonly IMapper mapper;
public SchedulesController(IScheduleRepository repository, IMapper mapper)
{
this.repository = repository;
this.mapper = mapper;
}
[HttpGet]
public IActionResult Get()
{
var result = mapper.Map<IEnumerable<Schedule>, IEnumerable<ScheduleDto>>(source: repository.items);
return new OkObjectResult(result);
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试班:
public class SchedulesControllerTests
{
[Fact]
public void CanGet()
{
try
{
//Arrange
Mock<IScheduleRepository> mockRepo = new Mock<IScheduleRepository>();
mockRepo.Setup(m => m.items).Returns(new Schedule[]
{
new Schedule() { Id=1, Title = "Schedule1" },
new …Run Code Online (Sandbox Code Playgroud)