NUnit+mock+moq单元测试

[TestFixture]
    public class InstantBatchBuyTest
    {
        private string _mallAbc;
        private string _itemCode;
        private int _quantity;
        private string _items;
        Mock mockCatalog;
        Mock mockShoppingCartService;

        [SetUp]
        public void Init()
        {
            _mallAbc = string.Empty;
            _itemCode = "18-001-0001";
            _quantity = 2;

            _items = "[{\"qty\":2,\"sku\":\"18-001-0001\"},{\"qty\":4,\"sku\":\"18-001-0002\"},{\"qty\":2,\"sku\":\"18-001-0003\"}]";

            var items = new List() { new ItemInfo { ItemCode = "18-001-0001" }, new ItemInfo { ItemCode = "18-001-0002" }, new ItemInfo { ItemCode = "18-001-0003" } };
            mockCatalog = new Mock();
            mockCatalog.Setup(s => s.GetItemByCodeList(It.IsAny>())).Returns(items); // 这些都是服务端的接口,此处我们可以设置返回值

            mockShoppingCartService = new Mock();
            mockShoppingCartService.Setup(s => s.CheckItemInventory("18-001-0001", 2)).Returns(true);
            mockShoppingCartService.Setup(s => s.CheckItemInventory("18-001-0002", 4)).Returns(true);
            mockShoppingCartService.Setup(s => s.CheckItemInventory("18-001-0003", 2)).Returns(true);
            mockShoppingCartService.Setup(s => s.InstantBuyForbiddenBuyProduct(items)).Returns(false);
        }


        [Test]
        public void 立即购买_单个商品()
        {
            var result = new InstantBuyAjaxResult();
            // Arrange
            var instanItemList = new List() { new InstantItemModel { ItemCode = _itemCode, Quantity = _quantity } };
            if (instanItemList.Any())
            {
                // Act
                result =
                    (new InstantBuyLogic(mockShoppingCartService.Object, mockCatalog.Object)).InstantBuy(
                        instanItemList);
            }

            // Assert
            Assert.AreEqual(result.Status, 1);
        }

        [Test]
        public void 立即购买_多个商品()
        {
            var result = new InstantBuyAjaxResult();
            // Arrange
            var instanItemList = JsonHelper.JsonToObject>(_items);
            if (instanItemList != null && instanItemList.Any())
            {
                // Act
                result =
                    (new InstantBuyLogic(mockShoppingCartService.Object, mockCatalog.Object)).InstantBuy(
                        instanItemList);
            }

            // Assert
            Assert.AreEqual(result.Status, 1);
        }
    }

需要添加Moq.dll、nunit.framework.dll引用,开发过程中结合Resharper,使用起来更加方便

转载于:https://www.cnblogs.com/cr7/p/3229420.html

你可能感兴趣的:(NUnit+mock+moq单元测试)