Sathish
Sathish

Reputation: 869

Why we create mock for interfaces in Unit testing

Why we mock interfaces while performing unit testing in .NET? Why not mock classes. Correct me if the question is silly.

Upvotes: 0

Views: 523

Answers (3)

Oded
Oded

Reputation: 499052

You mean mock objects. There is no such thing as a mock interface, there is a mock of an interface (or class).

They are used so you can concentrate on testing a class without also testing its dependencies.

Since unit tests are about testing the smallest unit of code (normally a class in .NET), you don't want your tests to execute code that does is not part of the class, this is where mocks come in.

The idea is that you use mocks instead of any implementation of a dependency of the class under test, thus ensuring that the code tested is only that of the class under test.

Upvotes: 2

Spyros
Spyros

Reputation: 48636

Testing concerns the behaviour of a certain unit. Since other parties are present when testing some cases, you would need a way to safely bypass them. In a way that your test is not affected. Mocks and stubs provide that ability.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500785

You don't create mock interfaces. You create interfaces which your production classes implement, and then you either create a test double manually, or you use a mocking framework to "pretend" to implement the interface in a programmable way. Those test doubles (manual or mocks) are then used when you're testing other production classes which have a dependency on the interface.

Some frameworks will let you mock classes to some extent, but usually they don't allow sealed classes to be mocked, or the behaviour of non-virtual methods to be specified with mock behaviour.

I'm not entirely sure this answers your question - if you could clarify the question, I'll try to clarify my answer accordingly...

Upvotes: 3

Related Questions