[英]Writing a unit test for a Builder Class
我正在编写一个项目,该项目需要一个 JSON 文件来反序列化它并构建数据并处理它们,然后将其保存到数据库中。 现在我想使用 Mock 为这个类编写一个单元测试,但我不知道该怎么做,因为在这个方法中我只均衡了我的 DTO 和数据库中的字段
这是我的订单 Dto
public class OrderDto
{
public int Code { get; set; }
public int CustomerCode { get; set; }
public int StoreCode { get; set; }
public string OrderDate { get; set; }
public string OrderStatus { get; set; }
public string DeliveryDate { get; set; }
}
这是我的订单生成器类
public class OrderBuilder
{
static PracticeEntities _context;
public OrderBuilder(PracticeEntities4 context)
{
_context = context;
}
public static CustomersOrder OrderBuild(OrderDto dto)
{
//using (var context = new PracticeEntities4())
//{
var oldStoreId = _context.Stores.FirstOrDefault(e => e.Code == dto.StoreCode).Id;
var oldCustomerId = _context.Customers.FirstOrDefault(e => e.Code == dto.CustomerCode).Id;
return new CustomersOrder()
{
OrderDate = Convert.ToDateTime(dto.OrderDate),
OrderStatus = dto.OrderStatus,
DeliveryDate = Convert.ToDateTime(dto.DeliveryDate),
CustomerId = oldCustomerId,
StoreId = oldStoreId,
Code = dto.Code
};
//};
}
}
由于您使用的是实体框架,我认为这篇文章会对您有所帮助: https : //docs.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking
创建您自己的测试替身——这种方法涉及编写您自己的上下文和 DbSet 的内存实现。 这使您可以对类的行为方式进行大量控制,但可能涉及编写和拥有合理数量的代码。
使用模拟框架创建测试替身——使用模拟框架(例如 Moq),您可以在运行时为您动态创建上下文和集合的内存实现。
因此,使用第一种方法,您可以使用特定数据模拟 db 调用并确保结果成功返回。
这些测试虽然不能保护业务错误,但可以保护您的代码免于丢失空检查和类似的运行时错误。
更新
首先要注意的是,不能对静态类进行单元测试。 因此,要测试的方法应修改如下所示。 此外,需要注入在PracticeEntities4
类中实现的 dbcontext 即IPracticeEntities4
接口,以便可以IPracticeEntities4
它。
public class PracticeEntities4:IPracticeEntities4, DbContext
{
....
}
public class ClassMethod2BTested
{
IPracticeEntities4 _context; //declare the context
public ClassMethod2BTested(IPracticeEntities4 context) // inject the context
{
_context=context; // set the context to local variable
}
public CustomersOrder OrderBuild(OrderDto dto)
{
//using (var context = new PracticeEntities4()) // remove this
{
var oldStoreId = _context.Stores.FirstOrDefault(e => e.Code == dto.StoreCode).Id;
var oldCustomerId = _context.Customers.FirstOrDefault(e => e.Code dto.CustomerCode).Id;
return new CustomersOrder()
{
OrderDate = Convert.ToDateTime(dto.OrderDate),
OrderStatus = dto.OrderStatus,
DeliveryDate = Convert.ToDateTime(dto.DeliveryDate),
CustomerId = oldCustomerId,
StoreId = oldStoreId,
Code = dto.Code
};
};
}
}
现在可以联合测试上述方法。
对于单元测试,请在此处查看示例: Mocking EF DbContext with Moq
添加
请检查此代码: github
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.