繁体   English   中英

如何使用Sqlite对xUnit测试ASP.NET 5

[英]How to xUnit Test an ASP.NET 5 with Sqlite

默认情况下,使用Microsoft.Data.Sqlite将尝试在ASP.NET 5项目(空模板)的wwwroot目录中找到数据库文件。

如何正确地xUnit测试这种项目? 如果我将此ASP.NET项目引用到我的xUnit测试项目中,则它一定会使用xUnit测试项目的目录作为基础。

更新1

我想使用xUnit进行集成测试。 感谢有人向我澄清了事情。

单元测试背后的想法是仅测试类的某些功能,而无需依赖它(如数据库,文件系统或网络)。

为了实现这一点,您需要在设计类时考虑到控制反转,并将必要的类型抽象为接口。

想象一下一个OrdersService类,该类可能获取订单数或所有订单的总和,而您想测试它的逻辑。

public interface IOrdersRepository 
{
    IEnumerable<Order> GetOrdersForCustomer(Guid customerId);
}

public class OrdersService : IOrdersService 
{
    private readonly IOrdersRepository ordersRepository;

    // pass the orders repository that abstracts the database access
    // as a dependency, so your OrdersService can be tested in isolation
    public OrdersService(IOrdersRepository ordersRepository)
    {
        this.ordersRepository = ordersRepository
    }

    public int GetOrdersCount(Customer customer) 
    {
        return ordersRepository.GetOrdersForCustomer(customer.Id).Count();
    }

    public decimal GetAllOrdersTotalSum(Customer customer)
    {
        return ordersRepository.GetOrdersForCustomer(customer.Id).Sum(order => order.TotalSum);
    }
}

然后在单元测试中,您将执行以下操作

[Fact]
public void CalculateOrderTotalSumTest() 
{
    // customer id we want to check 
    Guid customerId = new Guid("64f52c5c-44b4-4adc-9760-5a03d6f98354");

    // Our test data
    List<Order> orders = new List<Order>()
    {
        new Order() { Customer = new Guid("64f52c5c-44b4-4adc-9760-5a03d6f98354"), TotalSum = 100.0m),
        new Order() { Customer = new Guid("64f52c5c-44b4-4adc-9760-5a03d6f98354"), TotalSum = 50.0m)
    }

    // Create a mock of the IOrdersRepository
    var ordersRepositoryMock = new Mock<IOrdersRepository>();
    // Next you need to set up the mock to return a certain value
    ordersRepositoryMock
        .Setup( m => m.ordersRepositoryMock(It.Is<Guid>( cId => cId == customerId) )
        .Returns(orders);

    decimal totalSum = ordersRepositoryMock.Object.GetAllOrdersTotalSum(customerId);
    Assert.AreEqual(150.0m, totalSum, "Total sum doesn't match expected result of 150.0m");
    ordersRepositoryMock.VerifyAll();
}

这样,您无需数据库即可单独测试类。 如果在单元测试中需要数据库,文件系统上的文件或网络连接,那么在设计类型上就做得不好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM