views:

122

answers:

2

I need to mock just Method1 to test my process exception. How I can do that?

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;
        }
    }
}
+4  A: 
fooMock =  MockRepository.GenerateStub<IFoo>();
fooMock.Stub(x => x.Method1()).Return("Whatever");
Martin
It doesn't solve my problem, but give me the light. Thank you!
Zote
A: 

The interface is a red herring. You'll have to mock the implementation Foo and change Method1 to be virtual:

...
public virtual void Method1()
...

Use the throw extension to create the exception you wish to handle:

var fooMock = MockRepository.GenerateStub<Foo>();
fooMock.Expect(foo => foo.Method1()).Throw(new Exception());

var actual = fooMock.Method2();
Assert.IsNull(actual);

fooMock.VerifyAllExpectations();
Ed Chapel
I think you can only stub Interfaces ... (but I could be wrong)
Martin