user472292
user472292

Reputation: 329

Override Method Return Value

I want a certain method of an object to always return a certain value when running unit tests. For example.

In the unit test I want Method A to return "Bar", but in all other cases I want to return "Foo".

I don't think Mocking will work since you need to have the object reference ahead of time (at least with Moq). Any ideas?

Upvotes: 1

Views: 264

Answers (2)

Peter
Peter

Reputation: 27944

Mocking is the tool to use for this kind of scenario. Most mocking framework will enable you to mock object A without creating the instance. For example moles from Microsoft will enable you to implement the scenario you describe.

Moles

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 161002

If possible you should pass in Object A as a dependency into Object B. The dependency you can then mock out using Moq and make it return Bar when method A is called.

If object creation of A is done internally in B, then object B is not testable for this part (hence why you should pass in your dependencies).

Upvotes: 2

Related Questions