【发布时间】:2022-01-26 06:56:42
【问题描述】:
我不知道为什么这个测试失败了。我创建了一个新功能,手动测试它,它工作正常。 之后,我尝试创建测试,但总是失败。 我不知道为什么。 它只是应该清除数据库中超过 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) 中提供的日期
【问题讨论】:
-
这里的主要问题是NUnit是用于单元测试的,而你写的是集成测试。您为这项工作使用了错误的工具。
-
您是否同时运行测试? (这是现代单元测试框架中的默认设置,因为它可以在多核系统上节省大量时间),如果是这样,那可能是罪魁祸首,因为您的测试和逻辑看起来并不 concurrency-safe我。
-
我是根据另一个测试类似功能的测试编写的,它在那里工作,但它没有,我看不出有任何区别。
-
我发现了一个问题。 Created 没有从 2000 年获取日期,始终设置当前日期
-
但是我知道如何解决它