1

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;
        }
    }
}
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
Zote
  • 5,343
  • 5
  • 41
  • 43
  • try "you're only just a method, you're only just a method" in a sing-song voice ;-) – Steven A. Lowe Aug 12 '09 at 20:32
  • You shouldn't be mocking Method1() while testing Method2(), this would mean that you're testing the mock object. There's probably too much going on in one class and room to break it apart. (usually in these types of cases) – Chris Missal Aug 13 '09 at 05:30

2 Answers2

4
fooMock =  MockRepository.GenerateStub<IFoo>();
fooMock.Stub(x => x.Method1()).Return("Whatever");
Martin
  • 11,031
  • 8
  • 50
  • 77
0

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
  • 6,842
  • 3
  • 30
  • 44