简体   繁体   中英

Moq - how to access a class member when mocking?

Assume this class:

public class Foo
{
   public string Bar { get; set;}

   Foo()
   {
      this.Bar = "Hello world";
   }

   public void DoStuff()
   {
       this.Bar = "BAR" // imagine this is read from a memory stream
   }

}

I'd like to mock Foo and set it up so that I can introduce my own behaviour in DoStuff() - namely do some operations on the Bar member. But how can I access Bar on a callback from DoStuff() ?

What I tried: - Callbacks on DoStuff() don't seem to access the class state - I could setup the Bar getter, but this is too general as other operations read Bar as well

You wouldn't mock Foo for what you are doing. Mocks are used for providing tightly controlled concretions of dependencies within specific instances.

For example, if Foo had a member of type IBaz which was passed in the constructor, you could create a mock of IBaz where you tell IBaz how to react when Foo makes calls against its interface to trigger behaviour in Foo itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM