c# – 使用参数中的匿名函数验证函数调用
作者:互联网
我有一个类,一个服务和两个接口:
public class MyBasicObject
{
public MyBasicObject() { }
public int Id { get; set; }
public string Name { get; set; }
}
public interface ICacheProvider
{
T Get<T>(string key, Func<T> fetcher) where T:class;
}
public interface IMyBasicObjectRepository
{
MyBasicObject GetByName(string name);
}
public class MyBasicObjectService
{
public MyBasicObjectService(ICacheProvider cacheProvider,
IMyBasicObjectRepository repository)
{
CacheProvider = cacheProvider;
MyBasicObjectRepository = repository;
}
public ICacheProvider CacheProvider { get; set; }
public IMyBasicObjectRepository MyBasicObjectRepository { get; set; }
public MyBasicObject GetByName(string name)
{
return CacheProvider.Get<MyBasicObject>(name, () =>
MyBasicObjectRepository.GetByName(name));
}
}
使用RhinoMocks,我希望能够验证何时执行MyBasicObjectService.GetByName(“AnUniqueName”),CacheProvider.Get(“AnUniqueName”,()=> MyBasicObjectRepository.GetByName(“AnUniqueName”))也是如此.我有一个这样的夹具设置:
[TestFixture]
public class MyBasicObjectServiceFixture
{
[Test]
public void GetByNameShouldCallCacheProviderFunction()
{
// Arrange
MockRepository mock = new MockRepository();
IMyBasicObjectRepository repo = mock.DynamicMock<IMyBasicObjectRepository>();
ICacheProvider cacheProvider = mock.DynamicMock<ICacheProvider>();
MyBasicObjectService service = new MyBasicObjectService(cacheProvider, repo);
cacheProvider.Expect(p => p.Get<MyBasicObject>("AnUniqueName", () => repo.GetByName("AnUniqueName")));
mock.ReplayAll();
// Act
var result = service.GetByName("AnUniqueName");
// Assert
mock.VerifyAll();
}
}
我希望这个测试能够通过,但是当运行时,断言失败,通知我没有调用cacheProvider.Expect中布置的函数.我错过了什么.模拟和测试采用Func<>参数的方法
编辑:
所以,如果我这样做:
cacheProvider.Expect(p => p.Get<MyBasicObject>("AnUniqueName", () => repo.GetByName("AnUniqueName"))).IgnoreArguments();
(也就是说,将IgnoreArguments()方法添加到expect调用的末尾)
……测试通过就好了.我假设,这是传入的参数的一个问题.是否有一些我在调用缓存提供程序方法的期望中做错了但是它会在传入的匿名方法上窒息?
解决方法:
问题是两个匿名方法(Expect中的一个和GetByName中创建的一个是两个不同的对象,因此不相等.你可以通过部分匹配这样的参数来解决这个问题:
cacheProvider.Expect(p => p.Get<MyBasicObject>(Arg<string>.Is.Equal("AnUniqueName"), Arg <Func<MyBasicObject>>.Is.NotNull));
标签:c,anonymous-function,rhino-mocks 来源: https://codeday.me/bug/20190709/1408583.html