存储库不会从我的测试方法返回值

本文关键字:我的 测试方法 返回值 存储 | 更新日期: 2023-09-27 17:56:18

我是单元测试的新手,我正在尝试为以下服务方法编写单元测试:

public InventoryViewModel GetInventory(DateTime startDate, DateTime endDate, long roomServiceId)
{
    InventoryViewModel inv = new InventoryViewModel();
    var roomService = _unitOfWork.RoomServiceRepository.GetByID(roomServiceId);
    if (roomService == null)
        throw new InvalidOperationException("there is not the roomService");
        ....
    }
...
}
此方法

工作正常,但是当我从TestMethod调用此方法时,RoomServiceRepository不会返回roomService。我的测试方法如下所示:

[TestClass]
public class InventoryTest
{
    private UnityContainer _container;
    readonly MockObjectsSetup _mos = new MockObjectsSetup();
    private IInventoryService _inventoryService;
    [TestInitialize]
    public void SetupTest()
    {
        _container = new UnityContainer();
        _mos.Setup(_container);
        Config.UnityTestConfig.RegisterTypes(_container);
        _container.RegisterType<IInventoryService, InventoryService>();
        _inventoryService = (InventoryService)_container.Resolve(typeof(InventoryService));
    }
    [TestMethod]
    public void Dont_Change_NotSelected_PriceValues()
    {
        DateTime startDate = DateTime.Parse("6/21/2016");
        DateTime endDate = DateTime.Parse("6/22/2016");
        long roomServiceId = 17;
        InventoryViewModel invViewModel = new InventoryViewModel();
        invViewModel.isUpdatingBoardPrice = invViewModel.isUpdatingPrice = invViewModel.isUpdatingFloatAvailability = true;
        invViewModel.isUpdatingCertainAvailability = false;
        invViewModel.StartDate = startDate;
        invViewModel.EndDate = endDate;
        invViewModel.RoomServiceId = roomServiceId;
        invViewModel.CertainAvailability = 0;
        invViewModel.FloatAvailability = 8;
        var inv = _inventoryService.GetInventory(startDate, endDate, roomServiceId);
        ....
    }
}

存储库不会从我的测试方法返回值

您需要

停止在测试中依赖DI和IOC,并开始使用模拟。

例如,像RhinoMocks,但也有其他框架。

这个想法是,你准备你的服务,你模拟它们以返回通常来自数据库的数据,然后你运行一些功能,调用你想要测试的方法,并断言结果会发生什么。

实际上,您

是在说您不在乎数据来自何处,但它需要有一个受控的响应,这就是您在嘲笑的。你只关心功能。这有意义吗?