c# - Is there a way to create a mock object and only mock one of the Property, and let the others -


is there way create mock object , mock 1 of property, , let others (properties , methods) links original class, without having mock methods

test method -->

var test= new mock<test>().as<itest>(); test.callbase = true; test.setupget(m => m.datenow).returns(datetime.now.adddays(10)); double num= test.object.calc(); 

interface -->

public interface itest { double calc(); datetime datenow { get; } } 

class -->

public class test : itest {  public datetime datenow         {                         {                 return datetime.now.date;             }         } public double calc(){ datetime d = datetime.now.adddays(100); return (datenow - d).totaldays; } 

always num = 0.0;

yes, can, provided make use of both callbase call concrete class, , as<> target appropriate interface / base class:

var mockclass = new mock<myclass>().as<imyinterface>(); mockclass.callbase = true; mockclass.setupget(m => m.property1).returns("mock");  assert.areequal("mock", mockclass.object.property1); assert.areequal("myclass", mockclass.object.property2); 

as tested on set of entities:

public interface imyinterface {     string property1 { get; set; }     string property2 { get; set; } }  public class myclass : imyinterface {      public string property1     {         { return "myclass"; }         set {  }     }      public string property2     {         { return "myclass"; }         set { }     } } 

edit

why doesn't concrete class polymorphically call mocked overridden property?

this isn't moq specific - note default implementation of interface class sealed. if intend polymorphic behaviour on class properties, you'll need implement property virtual, so:

public interface itest {     datetime datenow { get; set; }     double calc(); }  public class test : itest {     public virtual datetime datenow // ** nb : virtual     { // .... 

edit

this should make clearer - try , without virtual keyword on datenow:

var test = new mock<test>().as<itest>(); test.callbase = true; test.setupget(m => m.datenow).throws(new notimplementedexception()); double num = test.object.calc(); 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -