我需要模拟Method1来测试我的进程异常。我怎么能这样做?
public interface IFoo
{
void Method1();
object Method2();
}
public class Foo : IFoo
{
public void Method1()
{
// Do something
}
public object Method2()
{
try
{
// Do something
Method1();
// Do somenthing
return new object();
}
catch (Exception ex)
{
// Process ex
return null;
}
}
}
答案 0 :(得分:4)
fooMock = MockRepository.GenerateStub<IFoo>();
fooMock.Stub(x => x.Method1()).Return("Whatever");
答案 1 :(得分:0)
界面是红鲱鱼。您必须模拟实现Foo并将Method1更改为虚拟:
...
public virtual void Method1()
...
使用throw扩展来创建您想要处理的异常:
var fooMock = MockRepository.GenerateStub<Foo>();
fooMock.Expect(foo => foo.Method1()).Throw(new Exception());
var actual = fooMock.Method2();
Assert.IsNull(actual);
fooMock.VerifyAllExpectations();