我不知道为什么这个测试失败。我创建了一个新功能,手动测试,它运行良好。之后,我尝试创建测试,但总是失败。我不知道为什么。它只需要从数据库中清除1.5年以上的所有记录,但变量historyToDelete总是有0条记录。有整个测试:
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeamsAllocationManager.Contracts.EmployeeWorkingTypeHistory;
using TeamsAllocationManager.Database;
using TeamsAllocationManager.Domain.Models;
using TeamsAllocationManager.Infrastructure.Handlers.EmployeeWorkingHistory;
namespace TeamsAllocationManager.Tests.Handlers.EmployeeWorkingHistory
{
[TestFixture]
public class ClearOldEmployeeWorkingTypeHistoryRecordsHandlerTest
{
private readonly ApplicationDbContext _context;
public ClearOldEmployeeWorkingTypeHistoryRecordsHandlerTest()
{
DbContextOptions<ApplicationDbContext> options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: GetType().Name)
.Options;
_context = new ApplicationDbContext(options);
}
[SetUp]
public void SetupBeforeEachTest()
{
_context.ClearDatabase();
var employeeWorkingTypeHistory1 = new EmployeeWorkingTypeHistoryEntity
{
EmployeeId = Guid.Parse("d6951ec1-c865-41bb-8b83-0fcd81745579"),
WorkspaceType = 0,
Created = new DateTime(2000, 01, 01)};
var employeeWorkingTypeHistory2 = new EmployeeWorkingTypeHistoryEntity
{
EmployeeId = Guid.Parse("8a6c4e1c-2c6d-4b70-a507-7bdae5f75429"),
WorkspaceType = 0,
Created = DateTime.Now
};
_context.EmployeeWorkingTypeHistory.Add(employeeWorkingTypeHistory1);
_context.EmployeeWorkingTypeHistory.Add(employeeWorkingTypeHistory2);
_context.SaveChanges();
}
[Test]
public async Task ShouldClearHistory()
{
// given
int numberOfHistoryToClear = 1;
int expectedInDatabase = _context.EmployeeWorkingTypeHistory.Count() - numberOfHistoryToClear;
var command = new ClearOldEmployeeWorkingTypeHistoryRecordsCommand();
var deletionDate = command.TodayDate.AddMonths(-18);
var historyToDelete = await _context.EmployeeWorkingTypeHistory
.Where(ewth => deletionDate > ewth.Created)
.ToListAsync();
var commandHandler = new ClearOldEmployeeWorkingTypeHistoryRecordsHandler(_context);
// when
bool result = await commandHandler.HandleAsync(command);
// then
Assert.IsTrue(result);
Assert.AreEqual(expectedInDatabase, _context.EmployeeWorkingTypeHistory.Count());
//Assert.IsFalse(_context.EmployeeWorkingTypeHistory.Any(ewth => historyToDelete.Contains(ewth.Id)));
}
}
}
若我发现它失败的原因,我会修复整个测试,但现在我被卡住了。
#更新1
我发现了一个问题。在SetupBeforeEachTest中创建dbContext时,将Created设置为2000.01.01。一切都很好,但当我从这开始到第一次测试时,当我检查数据库时,我总是有当前日期,而SetupBeforeEach(2021.12.27(中没有提供
创建记录时保存更改更新创建日期,因此如果您想更改创建日期以在将来进行测试,则需要先创建新记录,然后保存更改、更新并再次保存更改。
尝试调用ShouldClearHistory((方法中的SetupBeforeEachTest((方法。