Dependency injection, unit testing and information hiding

Suppose you have a class Foo with a private member of type Bar. You do not want users to know that the Foo implementation contains a panel, and you do not want users to create their own bar and pass it through the Foo constructor, any other method or configuration file.

Edit: The bar is also problematic in that it accesses resources that are independent of your test environment, such as a special database, network connection, or other process.

What do you do when you want to be able to unit test Foo? Is dependency injection possible? Does this mean that Bar and Foo are too closely related (although dependency is one way) and that this situation is never acceptable?

+3
source share
4 answers

[Disclaimer: I work at Typemock ]

You have three options:

  • Create an internal method that sets the Bar class - using InternalVisibleTo in the assemblyInf.cs file, you can enable tests to set this class.
  • Use DI to enter the Bar class, while modifying the test, this class is with a dummy or fake.
  • Use the Faking / Mocking framework, such as Typemock Isolator (.NET), which allows you to set fake behavior for objects created in another class using Isolate.Swap.NextInstance<Bar>.With(fakeBar);
+4
source

You never want to hide addictions if you can help.

, , Bar, , , : ( ) Bar Foo, .

(.. - ), Dror .

+5

Bar - Foo, , Foo.

EDIT: Bar , Foo, , Foo, .

+1

, . , . , new , .

, . , . , unit test .

, ? , ?

Edit

I understand, of course, that you can isolate him with some kind of trickery. However, these methods bypass public interfaces, limiting future flexibility and increasing the likelihood that someone will break it (mainly invalidating the usefulness of private members).

+1
source

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


All Articles