0

In an attempt to make my code friendly for unit testing, it seems wise to utilize depenency injection. This requires that any dependent class must implement an interface with the exact same set of methods.

I also see advice saying that I shouldn't have an interface for every class, but I don't see how I could possibly follow both pieces of advice. If I want unit testing, every single useful class must adhere to an interface.

Proof: Suppose there exists a class that does not implement any interfaces. If I am able to unit test my entire program, then no other code depends on this class. Therefore this class is useless and might as well be deleted.

Is there something I am misunderstanding? Is there a way to unit test without copy/pasting all of my classes into equivalently structured interfaces?

3 Answers 3

0

When unit testing, you usually just want to mock classes that make external calls (be it a database query or hitting an API). Consequently, you need to have an interface for these classes. However, a lot of times you may have random DTOs or utility classes that do small simple things and don't need to be mocked.

Sign up to request clarification or add additional context in comments.

Comments

0

Some languages have tools that let you mock classes without writing a corresponding interface; for instance, Python allows patching arbitrary classes in test code, and the Mockito library for Java can generate a mock object from any class.

There is a school of thought that says when writing unit tests, only the "leaves", i.e. classes and methods which don't invoke other classes within the application, should be unit tested in isolation, and classes that are involved in orchestrating the behavior of other classes should be tested at the acceptance or integration level. This style of testing avoids writing unit tests that depend on mocking most of the classes in your application, and so avoids the need to write interfaces. Martin Fowler's article on mocks covers some of the differences between different styles of testing regarding mocks.

Comments

0

In order to write effective tests, you do need seams in your code (a place that let's you break your dependencies apart) to allow you to control any dependencies in your code. Interfaces are possibly the most obvious way to do this, but you can use other techniques such as wrapping your dependency in a method on your class under test and declaring that method as protected virtual (c#) and overriding the class for your unit tests. There is a great series of videos on YouTube around TDD that deal with design decisions when doing TDD. Search for "is TDD dead".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.