我得到了执行基本CRUD活动的服务类,我想一起运行所有测试。
目前,我可以逐个进行测试。但是,如果我通过选择测试类来运行测试,那么它只是先运行随机测试并且未能通过其他测试显示错误:
The connection string property has not been initialized.
原因是我在我的服务中使用using
子句,并在第一次测试后删除了当前连接。
CashupService.cs
public class CashupService
{
private PJDbContext _context;
public CashupService(PJDbContext context)
{
_context = context;
}
public async Task<int> InsertCashUpRecord(CashupModel model)
{
using (IDbConnection conn = _context.Database.GetDbConnection())
{
var parameters = new
{
JobID = model.JobID
, Description = model.Description
, Amount = model.Amount
, User = model.UserCreated
};
return await conn.ExecuteAsync("dbo.InsertCashUpRecord", parameters, commandType: CommandType.StoredProcedure);
}
}
public async Task<IEnumerable<CashupModel>> GetCashUpRecords(bool Latest, DateTime? From, DateTime? To)
{
using (IDbConnection conn = _context.Database.GetDbConnection())
{
var parameters = new
{
Latest = Latest
, From = From
, To = To
};
return await conn.QueryAsync<CashupModel>("dbo.GetCashUpRecords", parameters, commandType: CommandType.StoredProcedure);
}
}
public async Task<int> InsertCashUpLog(CashupLogModel model)
{
_context.CashupLogs.Add(model);
return await _context.SaveChangesAsync();
}
}
如果我在2 Get方法中不使用using
子句,则错误消失。但AFAIK是一个很好的做法,我不想摆脱那个using
条款。
我的夹具初始化连接:
public PJFixture()
{
var optionsBuilder = new DbContextOptionsBuilder<PJDbContext>();
optionsBuilder.UseSqlServer("Data Source=MyServer;Initial Catalog=westwood;User Id=johnsmith;Password=xxx1234;");
context = new PJStudents.DbContexts.PJDbContext(optionsBuilder.Options);
}
public void Dispose()
{
context.Dispose();
}
public PJStudents.DbContexts.PJDbContext context { get; set; }
}
CashupServiceTests.cs
这里我在构造函数中创建了DbContext和Service,理论上,它不应该在运行另一个测试时再次创建吗?
public class CashupServiceTest : IClassFixture<PJFixture>
{
PJFixture _fixture;
CashupService _service;
public CashupServiceTest(PJFixture fixture)
{
_fixture = fixture;
_service = new CashupService(_fixture.context);
}
[Fact]
public async Task Should_Return_CashUpRecords_With_Latest()
{
var result = await _service.GetCashUpRecords(true, null, null);
Assert.NotEmpty(result);
}
[Fact]
public async Task Should_Return_CashUpRecords_With_Dates()
{
var result = await _service.GetCashUpRecords(false, new DateTime(2017, 3, 2, 10, 10, 10), DateTime.Now);
Assert.NotEmpty(result);
}
[Fact]
public async Task Should_Insert_CashupLog()
{
var model = new CashupLogModel();
model.Amount = 5;
model.UserCreated = "tester";
var result = await _service.InsertCashUpLog(model);
Assert.True(model.LogID > 0);
}
}
请您建议我应该如何编写测试并一次性运行它们?
如果我为每个测试创建另一个测试类,那么该错误就会消失,但我的测试文件中会有多个文件。
我可以知道最佳做法以及你们这样做的方式吗?