tags:

views:

43

answers:

2

I have a method that should only be called when a property of a specific object is set to false. This is its initial value. After the first call, the property is set to true, ensuring that the call is only ever made once.

However, when I mock the class that performs this change, the mock object does not change the property of the underlying object.

Is there a way to force a change of a property on an object is response to an Expectation being met?

Something along the lines of...

Expect.Call(mockedObject.TestMethod(underlyingObject)).NowDoThis(delegate() { underlyingObject.Processed = true; });
+2  A: 

Yes,

instead of your NowDoThis() call try Do()


Finally home so I can try out some code.

The trick is to cast the anonymous delegate to type Action that derrives from System.Delegate (type MethodInvoker should also work but that type is only available in System.Windows.Forms)

Here's the code. I'm more comfortable with the rhino mocks AAA syntax. Let me know if I have to convert it to Expect.Call syntax. I'm also using xunit.net, [Fact] just means [Test]

public interface Thingie
{
    bool Flag { get; set; }
    void DoSomething();
}

[Fact]
public void Test()
{
    var thingie = MockRepository.GenerateStub<Thingie>();

    thingie.Stub(x => x.DoSomething()).Do((Action) delegate { thingie.Flag = true; });

    Assert.False(thingie.Flag);

    thingie.DoSomething();

    Assert.True(thingie.Flag);
}
Mendelt
Hmm. When I do, I get an error, "Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type".
BlackWasp
A: 

Assuming mockedObject is, in fact, a mock object, you can simply set a return value for your property after the test method has been called:

bool isProcessed = false;
Expect.Call(mockedObject.TestMethod(underlyingObject))
   .Do(new Action(() => isProcessed = true));

SetupResult.For(mockedObject.Processed).Return(isProcessed);
Judah Himango