c# - Nsubstitute, changing the value of a property which is substituted -


i mock property in model specific value (because has private setter). call method changing property , check result. problem property return value. can somehow around problem?

here example:

public class tests {     [fact]     public void test1()     {         //arrange         var document = substitute.for<document>();         document.state.returns(documentstate.confirmed);          //act         document.close();          //assert         assert.equal(documentstate.closed, document.state); // fail, state still equals "documentstate.confirmed"     } }  public class document {     public virtual documentstate state { get; private set; }      public void close()     {         if (state != documentstate.confirmed)             throw new invalidoperationexception();          state = documentstate.closed;     } }  public enum documentstate {     draft,     confirmed,     closed } 

it's really bad idea mock class you're testing. can lead sorts of weird issues, not mention tightly coupled tests. if really want test scenario, can hand-roll testable stub:

public class testabledocument : document {     documentstate _state;     bool first = true;     public testabledocument(documentstate state) {         _state = state;     }     public override documentstate state {         {             if (first) {                 first = false;                 return _state;             }             return base.state;         }     } } 

then you'd instantiate in test, rather document.

[fact] public void test1() {     //arrange     var document = new testabledocument(documentstate.confirmed));      //act     document.close();      //assert     assert.equal(documentstate.closed, document.state);  } 

there may way of doing similar nsubstitute, don't know is.

generally speaking though, if you're mocking class you're testing there's chance you're either testing wrong thing or should @ refactoring code...


Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -