Bogdan Gavril MSFT
Bogdan Gavril MSFT

Reputation: 21458

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

Upvotes: 0

Views: 197

Answers (1)

toadflakz
toadflakz

Reputation: 7944

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.

Upvotes: 1

Related Questions