Unit Testing Mock/Stub definitions in Moq

后端 未结 4 677
终归单人心
终归单人心 2021-02-07 16:12

Any reading or advice I\'ve been given on Unit Testing has always suggested a distinct difference between the definition of a Mock and a Stub. My current understanding of these

4条回答
  •  猫巷女王i
    2021-02-07 16:42

    Indeed, Moq can create true stubs. From the Moq Quick Start page:

    * Setup a property so that it will automatically start tracking its value (also known as Stub):
    
      // start "tracking" sets/gets to this property
      mock.SetupProperty(f => f.Name);
    
      // alternatively, provide a default value for the stubbed property
      mock.SetupProperty(f => f.Name, "foo");
    
    
      // Now you can do:
    
      IFoo foo = mock.Object;
      // Initial value was stored
      Assert.Equal("foo", foo.Name);
    
      // New value set which changes the initial value
      foo.Name = "bar";
      Assert.Equal("bar", foo.Name);
    
    * Stub all properties on a mock (not available on Silverlight):
    
      mock.SetupAllProperties();
    

    IMHO, the distinctions between flavors of fakes is best thought of as a distinction between functions of those fakes rather than types of fakes, as a fake may take on multiple roles at once (e.g. can be a true mock and a saboteur all at once), and as no such distinction is necessary for using a mock framework. (I should blog about this!)

提交回复
热议问题