tags:

views:

88

answers:

1

What is the correct way for dealing with interfaces the expose set-only properties with Moq? Previously I've added the other accessor but this has bled into my domain too far with random throw new NotImplementedException() statements throughout.

I just want to do something simple like:

mock.VerifySet(view => view.SetOnlyValue, Times.Never());

But this yields a compile error of The property 'SetOnlyValue' has no getter

+5  A: 
public class Xyz
{
    public virtual string AA { set{} }
}
public class VerifySyntax
{
    [Fact]
    public void ThisIsHow()
    {
        var xyz = new Mock<Xyz>();
        xyz.Object.AA = "bb";
        // Throws:
        xyz.VerifySet( s => s.AA = It.IsAny<string>(), Times.Never() );
    }
}
public class SetupSyntax
{
    [Fact]
    public void ThisIsHow()
    {
        var xyz = new Mock<Xyz>();
        xyz.SetupSet( s => s.AA = It.IsAny<string>() ).Throws( new InvalidOperationException(  ) );
        Assert.Throws<InvalidOperationException>( () => xyz.Object.AA = "bb" );
    }
}
Ruben Bartelink
+1 - Having read this, I deleted my answer since it seems to be what the OP wants.
Lee
@Lee: Cool, ta (I know I did a double take reading the question too!)
Ruben Bartelink
Thanks Ruben, I never would've randomly decided to put an It.IsAny expression next to a line that resharper says is a compile error!
Chris Marisic
@Chris Marisic: I know you're only joking, but I inferred this from the [cheat sheet](http://code.google.com/p/moq/wiki/QuickStart) (specifically the `VerifySet` example, the fact that the lambda expression was doing a get and needed to do a set. Doing a set to something specific would filter the calls to only include the specific values used. Cheat Sheet FTW!
Ruben Bartelink
I did know you could specifically test for setting but I never though that would actually change the method overload that's being called by SetupSet to get around the compile error.
Chris Marisic
@Chris Marisic: Not sure if I'm explaining myself clearly. I mean that the Expression `view => view.SetOnlyValue` invokes the getter whereas something like `view => view.SetOnlyValue = 0` will invoke the setter. To avoid having to use the `It` stuff, the first style (getter) in the context of a `Setup/VerifySet` gets interpreted as referring to the setter, even though the underlying code is a getter invocation. There's no magic of the kind I feel you're interpreting my previous answer as suggesting.
Ruben Bartelink