Stand-alone example and development for interface-based programming

In response to this question here, Jon Skeet answered: →

You can test through mockery very easily (without having to mock classes that get ugly)

I would like to get a better understanding with a separate example, which will examine this aspect ... both the scripts before (ugly) and after (based on the interface) in C #.

And also, in addition, if there is an example in the BCL.NET Framework itself, that would be great

+4
source share
2 answers

Say that you have this method to extract all the names of people from a file:

string[] GetNamesFrom(string path) { } 

To test this method, you need to specify the path name to an existing file that needs some configuration.

Compare this with this method:

 string[] GetNamesFrom(IFile file) 

If the IFile contains the GetContents() method, then your "real" implementation of this interface can access the file system, and your mock class can simply return your test input.

Using a mock library such as moq ( http://code.google.com/p/moq/ ) becomes very simple:

 var fileMock = new Mock<IFile>(); fileMock.Setup(f => f.GetContents()).Returns(testFileContents)); Assert.Equals(expectedNameArray, GetNamesFrom(fileMock.Object)); 

Writing a file to the file system before testing may not seem like many settings, but if you use many tests, it becomes a mess. Using interfaces and taunting, all settings occur in your test method.

+3
source

Modifying classes can become ugly if you refactor existing code. Imagine a class:

 public class A { private B _instanceOfB; public void DoSomethingWithInstanceOfB() { // do something with _instanceOfB } } 

If you want to make fun of A, you need to not only extract the interface and refactoring all your code, but you may also need to start mocking B. And so on, potentially ad infinitum, in your enterprise settings. A concrete example would be if B is a class that controls access to a resource like a database.

0
source

Source: https://habr.com/ru/post/1334465/


All Articles