有一个功能:
public class MyCacheClass : ICache
{
public void T GetObject<T>(Func<T> func)
{
T t;
...
t = func();
...
return t;
}
}
public class MyWorkClass : IWork
{
public Object MyWorkMethod(string value)
{
return new object();
}
}
可以通过以下方式调用这些函数:
public class MyTestableClass
{
public void MyTestableFunc(ICache cache, IWorkClass work)
{
string strVal="...";
...
Object obj = cache(()=>work.MyWorkMethod(strVal));
...
}
}
有必要为此编写一个UnitTest(带有Moq),并检查传递给'MaCacheClass.GetObject'的参数是否正确。
应该是这样的:
[TestMethod]
public void MyTest()
{
Mock<ICache> mockCache = new Mock<ICache>();
Mock<IWorkClass> mockWorkClass = new Mock<IWorkClass>();
MyTestableClass testable = new MyTestableClass();
testable.MyTestableFunc(mockCache.Object, mockWorkClass.Object);
// should I check if 'MyCacheClass' was called with proper parameter?
mockCache.Verify(mock=>mock.GetObject(...)).Times.Once());
}
如何提供适合“ lambda函数”的参数?
还有其他选择吗?
任何想法都欢迎。
最佳答案
选项之一可能是:相反,在Funct参数上传递一些使用'GetObject'函数实现接口的对象,例如:
public interface IGetObject
{
T GetObject<T>();
}
public class MyGetObject : IGetObject
{
public MyGetObject()
{
}
public void Init(string strVal, Func<string, T> func)
{
_strVal = strVal;
_func = func;
}
public T GetObject<T>()
{
return _func(_strVal);
}
}
public class MyCacheClass : ICache
{
public void T GetObject<T>(IGetObject getter)
{
T t;
...
t = getter.GetObject<T>();
...
return t;
}
}
public class MyTestableClass
{
public void MyTestableFunc(ICache cache, IWorkClass work)
{
string strVal="...";
IGetObject getter = UnityContainer.Resolve<IGetObject>();
getter.Init(strVal, str=>work.MyWorkMethod(str));
...
Object obj = cache.GetObject(getter);
...
}
}
我猜在这种情况下,我们还需要将UnityContainer注入到测试对象中,因此将是这样的:
[TestMethod]
public void MyTest()
{
Mock<ICache> mockCache = new Mock<ICache>();
Mock<IWorkClass> mockWorkClass = new Mock<IWorkClass>();
Mock<IGetObject> mockGetter = new Mock<IGetObject>();
mockGetter.Setup(mock=>mock.GetObject()).Return(new Object());
MyTestableClass testable = new MyTestableClass();
testable.MyTestableFunc(mockCache.Object, mockWorkClass.Object);
// should I check if 'MyCacheClass' was called with proper parameter?
mockCache.Verify(mock=>mock.GetObject(mockGetter.Object)).Times.Once());
}
并为'MyCacheClass'的'GetObject'方法提供额外的测试,将检查它是否调用IGetObject参数的'GetObject'方法...
附言有点复杂的解决方案...因此,如果有人看到更好的解决方案,请告知!
关于.net - 如何使用Moq测试Lambda函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3752565/