Moq在方法中设置变量

时间:2014-11-09 18:35:45

标签: c# unit-testing mocking moq

我有以下方法试图测试,但即使我尝试设置它们,我的变量也是null。

        public void Cancel(Guid id)
        {
            var order = _orderRepository.Find(o => o.Id == id); ** This never gets set, even with the setup below.**
            if (order == null) return;  ** Test Fails here. Returns and all assertions fails.**

            order.Status = OrderStatus.Cancelled;
            _orderRepository.Update(order);
        }

        [SetUp]
        public void Setup()
        {
            _orderRepositoryMock = new Mock<IRepository<Order>>();
            _accountServiceMock = new Mock<IAccountService>();

            _orderService = new OrderService(_accountServiceMock.Object, _orderRepositoryMock.Object);

            order = new Order()
            {
                Id = Guid.NewGuid(),
                Customer= new ApplicationUser()
                {
                    Id = Guid.NewGuid().ToString(),
                    Email = "test@test.com",
                    FirstName = "Tester",
                    LastName = "Test",
                    Address = "123 45 Ave",
                    City = "ABCVille",
                    PhoneNumber = "1-888-888-8888",
                    PostalCode = "T3J 0A4",
                    Province = "Super"
                },
                OrderAddons = new List<OrderAddon>(),
                Total = 363.99m,
                Status = OrderStatus.Created
            };
        }

    [Test]
    public void CancelShouldCallRepositoryWhenValid()
    {
        //var order ... (test data, in setUp)
        var id = Guid.NewGuid();
        order.Id = id;

        // Repository Setup
        _orderRepositoryMock.Setup(x => x.Find(o => o.Id == id)).Returns(order);

        var wasOrderStatusUpdatedCorrectly = false;
        _orderRepositoryMock.Setup(x => x.Update(order))
            .Callback((Order o) =>
            {
                wasOrderStatusUpdatedCorrectly = o.Status == OrderStatus.Cancelled;
            });

        // Test Service
        _orderService.Cancel(id);

        // Test Assertions
        _orderRepositoryMock.Verify(x => x.Find(o => o.Id == It.IsAny<Guid>()), Times.Once);
        _orderRepositoryMock.Verify(x => x.Update(order), Times.Once);
    }

无论如何都要测试“var order”吗?我也尝试过SetupGet,似乎没有用,Moq对我来说是新手,所以如果这简单易行,请提前原谅我。

1 个答案:

答案 0 :(得分:1)

我认为问题是存储库的Expression方法所期望的Find。试试这个:

_orderRepositoryMock
    .Setup(x => x.Find(It.IsAny<Expression<Func<Order, bool>>>()))
    .Returns(order);

我只是猜测Expression<>的类型参数,但希望这会有所帮助。