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

时间:2016-07-09 09:16:21

标签: c# unit-testing testing unit-of-work

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

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。我的testMethod看起来像这样:

[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);

        ....
    }
}

1 个答案:

答案 0 :(得分:0)

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

例如RhinoMocks之类的东西,但也有其他框架。

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

实际上,你说你不关心数据的来源,但它需要有一个受控制的响应,这就是你在嘲笑的东西。你只关心功能。这有意义吗?

相关问题