【问题标题】:Repository don't return value from my Test Method存储库不从我的测试方法返回值
【发布时间】:2016-07-09 09:16:21
【问题描述】:

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

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

        ....
    }
}

【问题讨论】:

  • 你有没有嘲笑过你的inventoryService,你有什么例外吗?
  • 我没有模拟它,正如我所说,我是新手,我不知道如何模拟服务。

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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多