Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!

Is it possible to mock the set action of a property?

0 votes

I am using winForms, VS2015 and typemock isolator I was trying to mock out a call to a property setter but I only see the getter being mocked. Is there a way to intercept the call to the setter? (a way to control calls to the setter, not just the example here where trying to throw the exception)

Here is a simple class:

 public class PhotonTorpedo
        public int EnergyLevel
            get { return 5; }
        public PhotonTorpedo(){}
I would like to fake this class, and when the setter is called, throw an exception. But I don't see how to do this. Sample test:
public void SetterTest()
    var fakeTorpedo = Isolate.Fake.AllInstances<PhotonTorpedo>();
    Isolate.WhenCalled(() => fakeTorpedo.EnergyLevel).WillThrow(new Exception(""));
    string msg = "";
    var testTorpeo = new PhotonTorpedo();
        testTorpeo.EnergyLevel = 100;
    catch (Exception ex)
        msg = ex.Message;
    Assert.AreNotEqual(msg, "");
asked Aug 29 by meansala (160 points)
edited Aug 29 by meansala

1 Answer

0 votes

Hi Meansala,

Have you tried using:

Isolate.NonPublic.Property.WhenSetCalled(myInstance,"EnergyLevel ").WillThrow(new Exception(""));


answered Aug 30 by Raphy (1,090 points)
Thanks Rahpy - this does work, but it is a bit misleading that the .NonPublic is called for a public property - or am I missing something.

I'm sorry, I didn't see it was public.

To fake a public setter you can use:

Isolate.WhenCalled(() => fakeTorpedo.EnergyLevel=0).WillThrow(new Exception(""));


Isolate.WhenCalled(() => {fakeTorpedo.EnergyLevel=0;}).WillThrow(new Exception(""));

Excellent - this works! Thanks Raphy