1. 程式人生 > >Moq 在.net Core 單元測試中的使用

Moq 在.net Core 單元測試中的使用

Moq,主要用來偽造介面的實現類,實現方法,屬性

moq

The most popular and friendly mocking framework for .NET

What?

Moq (pronounced "Mock-you" or just "Mock") is the only mocking library for .NET developed from scratch to take full advantage of .NET Linq expression trees and lambda expressions, which makes it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn't require any prior knowledge or experience with mocking concepts.

Github:https://github.com/moq/moq4

常用方法彙總:

   定義Mock物件

  1.new Mock<IFoo>();

   設定mock物件返回值,返回固定值或者ThrowException

  1.mockInstance.SetUp().Returns() 

    mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

  2.mockInstance.SetUpSet()

  mock.SetupSet(s => s.Name = "zhangsan");

 3.mockInstance.SetupProperty()    SetupProperty方法返回mockInstance物件,可以繼續.方法,方便多次設定

  mock
   .SetupProperty(f => f.Name, "haha")
   .SetupProperty(f => f.Add(6), false)
   .SetupProperty(f => f.Bar, new Bar());

<h6>合計