Controller:html
namespace WebApplication1.Controllers測試
{this
public class TestController : Controllerspa
{htm
public TestController(IService service)blog
{ip
this.Service = service;get
}string
public IService Service { get; set; }it
// GET: Test
public virtual ActionResult Index()
{
var result = this.Service.Foo();
ViewBag.res = result;
return View();
}
}
}
測試代碼:
namespace MyTest
{
public class Class1
{
[Fact]
public void IndexTest()
{
var mock = new Mock<IService>();
mock.Setup(s => s.Foo()).Returns("我是模擬的");
TestController controller = new TestController(mock.Object);
ViewResult result = controller.Index() as ViewResult;
Assert.Equal("我是模擬的", result.ViewBag.res);
}
}
}
利用Mock實現IService裏指定的方法,咱們實現了Foo方法。再調用TestController裏Index方法時,裏的Foo方法實際上是我用Mock模擬的一個方法並非真實項目裏的方法。
Controller:
namespace WebApplication1.Controllers
{
public class TestController : Controller
{
public TestController(IService service)
{
this.Service = service;
}
public IService Service { get; set; }
// GET: Test
public ActionResult Index()
{
this.Service.Foo();
return View();
}
}
}
測試代碼
namespace MyTest
{
public class Class1
{
[Fact]
public void IndexTest()
{
var mock = new Mock<IService>();
mock.Setup(s => s.Foo());
TestController controller = new TestController(mock.Object);
ViewResult result = controller.Index() as ViewResult;
mock.Verify(s => s.Foo());
Assert.NotNull(result);
}
}
}
當模擬的方法沒有返回值的時候咱們要肯定方式是否執行了,能夠使用mock.Verify();來判斷方法時候被調用,使用方法如上。也能夠在設置模擬方法是指定是否驗證被調用,例如:
利用Verifiable()
mock.Setup(s => s.Foo()).Verifiable();
mock.Verify();
Ps:VerifyAll()是驗證全部的方法,不須要指定
利用It.Is<>()對參數作一個驗證,例如
It.Is<int>(i => i == 1),參數是1的int類型
mock.VerifyAll();
給屬性設置默認值:
mock.Setup(s => s.Lala).Returns("12390")
或
mock.SetupProperty(s => s.Lala, "12398");
驗證:
mock.SetupSet(s => s.Lala = "1232");//設置指望值
mock.VerifyAll();//驗證Controller裏的賦值是否與指望值一致
或
Action<IService> action = i => { i.Lala = "1232"; };
mock.VerifySet(action);
Ps:驗證是常量值也能夠使用It類裏的方法代替,例如
It.Is<string>(p => p == "33")
驗證是否被調用:
mock.VerifyGet(s => s.Lala);
或
mock.Setup(s => s.Lala).Verifiable();
mock.Verify();
或
mock.Setup(s => s.Lala)
mock.VerifyAll();
跟蹤屬性值:
mock.SetupProperty(s => s.Lala, "00");//這樣設置屬性就能夠被跟蹤,就能夠被修改
var obj = mock.Object;
obj.Lala = "90";//修改跟蹤的屬性
Ps:mock.Setup(s => s.Lala).Returns("12390"),設置屬性不會被跟蹤
模擬受保護的方法:
var mock = new Mock<Bar>();
mock.Protected().Setup<string>("Ox").Returns("321");
var res = mock.Object;
直接用mock的Setup,是無法模擬protected方法的,mock.Protected()就是爲了解決這個問題的。
Ps:引用命名空間using Moq.Protected;
測試私有方法:
Bar bar = new Bar();
var barPrivate = new PrivateObject(bar);
var result = barPrivate.Invoke("Pp");
Ps:引用Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll,路徑是C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PublicAssemblies\(根據vs版本不一樣有所不一樣)下,須要手工添加引用
參考文章:
http://www.cnblogs.com/darrenji/p/3869602.html#a
http://www.cnblogs.com/haogj/archive/2011/07/22/2113496.html
http://www.cnblogs.com/gossip/archive/2012/05/16/2503477.html