1.创建net core MSTest测试类
2.创建一个类库来存放两个类
3.在类库下新建两个类:
-- Item.cs
using System; using System.Collections.Generic; using System.Text; namespace AppCms.Models { public class Item { public string Name { get; set; } public decimal Price { get; set; } } }
-- ShoppingCart.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AppCms.Models { public class ShoppingCart { public int UsreID { get; set; } public string UserName { get; set; } public DateTime LastUpdata { get; set; } public List<Item> Items { get; set; } public decimal Total { get { return Items.Sum(i => i.Price); } } } }
4.在测试类下新建一个测试类
测试类:
using System; using System.Collections.Generic; using System.Text; using AppCms.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AppCms.Test { [TestClass] public class Shopping_UnitTest { [TestMethod] public void StringTst() { var item1 = new Item { Name = "Fruit", Price = 14.99M }; var item2 = new Item { Name = "tom", Price = 12.00M }; decimal y = 50.22M; var cart = new ShoppingCart { Items = new List<Item> { item1, item2 } }; //传入item参数值 var x = cart.Total; // Sum //Assert.AreEqual(x, y); //比较是否相等,x!=y,测试不通过 Assert.AreEqual(x, item1.Price + item2.Price); // x与Sum(item1+item2)的值相等,测试通过 } } }
测试结果:
5.跳过测试类中的莫个方法:[TestCategory("StringSum")]