使用以下界面:
public interface IRepository<T>
{
T FirstOrDefault(Func<T, bool> predicate);
}
如此实施:
private IRepository<Foo> Repository {get;set;}
public FooService(IRepository<Foo> repository)
{
Repository = repository;
}
public void Foo(int bar)
{
var result = Repository.FirstOrDefault(x => x.Id.Equals(bar));
if (result == null)
{
throw new Exception("Returned null, not what I expected!");
}
}
如果我写这样的测试:
repos = MockRepository.GenerateMock<IRepository<Foo>>(null);
repos.Expect(x => x.FirstOrDefault(y => y.Id.Equals(Arg<int>.Is.Anything))).Throw(new Exception("This exception should be thrown!"));
FooService f = new FooService(repos);
f.Foo(1);
//expecting exception to be thrown
我没有得到预期的异常抛出,所以我假设模拟调用被忽略/未被调用。
但是,如果我添加IgnoreArguments()
,则 被调用,我确实得到了预期的异常。
repos.Expect(x => x.FirstOrDefault(y => y.Id.Equals(Arg<int>.Is.Anything))).IgnoreArguments().Throw(new Exception("This exception should be thrown!"));
关于我做错了什么的想法?