我有一个使用EFcore的ABPZero框架实现的API。我已经按照文档中的建议在内存db中使用sqlite进行了集成测试。但是,当我尝试使用模拟对同一API进行单元测试时,我感到很困惑[假设模拟的执行速度更快]
我对那个方法有不同的看法。我应该在测试用例上嘲笑服务或存储库吗?
public PagedResultDto<PatientSearchDTO> Search(PatientInpu
PatientInput)
{
List<PatientSearchDTO> patientSearch = new
List<PatientSearchDTO>();
int totalCount=0;
try
{
var filterText = PatientInput.Filter.Trim().ToLower();
//Get the patients filtered usinng the filter text.
var result = this._demoRepository.GetAll().Where(x =>
x.Dem_Firstname.ToLower().Contains(filterText)
);
var treatment = _treatmentRepository.GetAll();
// Get the treatments for the pateints we fetched.
var demotreatment = (from tdemo in result
join treat in treatment on tdemo.Dem_Acu_Id equals treat.trm_acu_id into g1
from treat in g1.DefaultIfEmpty()
select new
{
Acu_Id = tdemo.Dem_Acu_Id,
FirstName = tdemo.Dem_Firstname.Trim(),
Surname = tdemo.Dem_Surname.ToUpper().Trim() + (string.IsNullOrWhiteSpace(tdemo.Dem_Alias) ? string.Empty : " (" + tdemo.Dem_Alias.Trim() + ")"),
MaidenName = tdemo.Dem_Maidname.Trim(),
DOB = tdemo == null ? DateTime.MinValue : tdemo.Dem_Dob,
RegistrationNumber = tdemo.Dem_RegNo == null ? string.Empty : tdemo.Dem_RegNo.Trim(),
Photo = tdemo.Dem_Photo,
TreatmentStartDate = treat == null ? Convert.ToDateTime("1900-01-01 00:00:00.000") : Convert.ToDateTime(treat.trm_tr_startdate)
});
这是测试的构造函数,
public PatientServiceTests()
{
service = LocalIocManager.Resolve < IPatientService >();
//creating set up data.
SetUp();
}
private void SetUp()
{
//Arrange
UsingIdeasDbContext(context =>
{
context.Demos.Add(new TDemo
{
Id = 1,
Dem_Acu_Id = "1",
Dem_Firstname = "Jack",
Dem_Surname = "Jill",
Dem_Maidname = "",
Dem_Dob = DateTime.UtcNow.AddYears(-30),
Dem_Alias = "JJ",
Dem_RegNo = "123456"
});
context.TTreatment.Add(new TTreatment
{
trm_acu_id = "1",
trm_cycle = "4207-1",
trm_tr_startdate = DateTime.UtcNow.AddMonths(-1),
});
}
[Fact]
public void Should_SearchPatients()
{
PatientInpu input = new PatientInpu () { Filter = "ja",
Sorting = "FirstName ASC", SkipCount = 0, MaxResultCount = 10 };
var result = service.Search(input);
result.Items.Count.ShouldBe(1);
}
对这种方法进行单元测试的最佳方法是什么?在内存还是模拟?
答案 0 :(得分:0)
理想情况下,您应该在数据库实现上有一个抽象层。您的呼叫者不需要知道实施细节。
话虽如此,通过接口公开数据库功能,并在进行单元测试时模拟出接口/服务(使用时可以使用Moq等模拟框架或编写自定义模拟)。