模拟框架,支持使用委托作为参数模拟方法

时间:2012-02-10 14:32:12

标签: c# delegates mocking moq

我对Moq非常满意,直到我需要测试一个将委托作为参数并获得UnsupportedException的方法。该问题还提到here和Moq issue list

有没有支持这种嘲弄的框架?

例如:

/// 
/// Interfaces
///

public interface IChannelFactory<T> {
    TReturn UseService<TReturn>(Func<T, TReturn> function);
}

public interface IService {
    int Calculate(int i);
}

///
/// Test
///

Mock<IChannelFactory<IService>> mock = new Mock<IChannelFactory<IService>>();

// This line results in UnsupportedException
mock.Setup(x => x.UseService(service => service.Calculate(It.IsAny<int>()))).Returns(10);

3 个答案:

答案 0 :(得分:4)

我不太确定你要做什么,但这会使用你的Moq 4接口进行编译和运行:

var mock = new Mock<IChannelFactory<IService>>();

mock.Setup(x => x.UseService(It.IsAny<Func<IService, int>>())).Returns(10);

int result = mock.Object.UseService(x => 0);

Console.WriteLine(result);  // prints 10

另请参阅this answer了解更复杂的案例。

答案 1 :(得分:1)

我最近遇到了同样的问题,这里是如何使用moq(v4.0.10827)测试正确的方法并调用参数。 (提示:你需要两层模拟。)

//setup test input
int testInput = 1;
int someOutput = 10;

//Setup the service to expect a specific call with specific input
//output is irrelevant, because we won't be comparing it to anything
Mock<IService> mockService = new Mock<IService>(MockBehavior.Strict);
mockService.Setup(x => x.Calculate(testInput)).Returns(someOutput).Verifiable();

//Setup the factory to pass requests through to our mocked IService
//This uses a lambda expression in the return statement to call whatever delegate you provide on the IService mock
Mock<IChannelFactory<IService>> mockFactory = new Mock<IChannelFactory<IService>>(MockBehavior.Strict);
mockFactory.Setup(x => x.UseService(It.IsAny<Func<IService, int>>())).Returns((Func<IService, int> serviceCall) => serviceCall(mockService.Object)).Verifiable();

//Instantiate the object you're testing, and pass in the IChannelFactory
//then call whatever method that's being covered by the test
//
//var target = new object(mockFactory.Object);
//target.targetMethod(testInput);

//verifying the mocks is all that's needed for this unit test
//unless the value returned by the IService method is used for something
mockFactory.Verify();
mockService.Verify();

答案 2 :(得分:0)

看看摩尔人。它支持代表作为模拟。

Moles

相关问题