NUnit+mock+moq单元测试
[TestFixture] public class InstantBatchBuyTest { private string _mallAbc; private string _itemCode; private int _quantity; private string _items; Mock<ICatalogService> mockCatalog; Mock<IShoppingCartService> 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<ItemInfo>() { new ItemInfo { ItemCode = "18-001-0001" }, new ItemInfo { ItemCode = "18-001-0002" }, new ItemInfo { ItemCode = "18-001-0003" } }; mockCatalog = new Mock<ICatalogService>(); mockCatalog.Setup(s => s.GetItemByCodeList(It.IsAny<List<string>>())).Returns(items); // 这些都是服务端的接口,此处我们可以设置返回值 mockShoppingCartService = new Mock<IShoppingCartService>(); 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<InstantItemModel>() { 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<List<InstantItemModel>>(_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,使用起来更加方便