0

使用下面的界面:

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!"));

关于我做错了什么有什么想法吗?

4

0 回答 0