gpt4 book ai didi

c# - 为构建器类编写单元测试

转载 作者:行者123 更新时间:2023-12-04 15:35:42 24 4
gpt4 key购买 nike

我正在编写一个项目,该项目采用 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
};
//};
}


}

最佳答案

已更新

首先要注意的是静态类不能进行单元测试。因此,要测试的方法应修改如下所示。此外,需要注入(inject)在 PracticeEntities4 类中实现的 dbcontext 即 IPracticeEntities4 接口(interface),以便可以模拟它。

 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

关于c# - 为构建器类编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com