使用moq来模拟一些方法

我有以下的方法:

public CustomObect MyMethod() { var lUser = GetCurrentUser(); if (lUser.HaveAccess) { //One behavior } else { //Other behavior } //return CustomObject } 

我想嘲笑IMyInterface.GetCurrentUser ,以便在调用MyMethod我可以到一个代码path来检查它。 如何用Moq做到这一点?

我正在做以下事情:

 var moq = new Mock<IMyInterface>(); moq.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser); //act var lResult = moq.Object.MyMethod(); 

但由于某种原因lResult始终为null ,当我试图在debugging中进入MyMethod ,我总是跳到下一个语句。

这被称为部分模拟,我知道在moq中执行它的方式需要嘲笑类而不是接口,然后将模拟对象上的“Callbase”属性设置为“true”。

这将需要使您正在testing的课程的所有方法和属性都是虚拟的。 假设这不是问题,那么你可以写一个像这样的testing:

  var mock = new Mock<YourTestClass>(); mock.CallBase = true; mock.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser); mockedTest.Object.MyMethod(); 

扩展李的答案 ,

你不需要使你的课堂上的所有方法和属性都变成虚拟的,而只需要你想要的那些方法和属性。

此外,应该指出,你应该嘲笑你的课程的具体实施。

var mock = new Mock<YourTestClass>(); // vs. var mock = new Mock<IYourTestInterface>();

如果你的类没有默认的构造函数,你还需要指定parameter passing给它:

 var mock = new Mock<YourTestClass>(x, y, z); // or var mock = new Mock<YourTestClass>(MockBehavior.Default, x, y, z); 

其中x, y, z分别是构造函数的第一,第二和第三个参数。

最后,如果你正在寻找模拟的方法是受保护的,你将需要包括Moq.Protected

 using Moq.Protected; TReturnType returnValue = default(TReturnType); mock.Protected() .Setup<TReturnType>("YourMockMethodName", It.IsAny<int>()) // methodname followed by arguments .Returns(returnValue); 

我也有类似的情况。 我发现下面的代码给了我更多的灵活性,从一些特定的接口实现中使用mocked方法和实际方法:

 var mock = new Mock<ITestClass>(); // Create Mock of interface // Create instance of ITestClass implementation you want to use var inst = new ActualTestClass(); // Setup to call method of an actual instance // if method returns void use mock.Setup(...).Callback(...) mock.Setup(m => m.SomeMethod(It.IsAny<int>()) .Returns((int x) => inst.SomeMethod(x)); 

现在,您可以使用实际的方法,但也可以使用诸如“validation”之类的内容来查看被调用的次数。