Why is there nothing special about the internal constructor?

This is disabling this closed-ended question , I had an answer, but it was closed before I could answer. Here is an updated version of the question:

Why should a class have an internal constructor that just sets the properties?

public class SomeClass { public SomeClass() : this(new SomeOtherClass()) { } internal SomeClass(SomeOtherClass c) { _someField = c; } private SomeOtherClass _someField; protected void SomeMethod() { var foo = _someField.Bar(); } } 

What is the advantage of this, why don't you just do:

 public class SomeClass { public SomeClass() { _someField = new SomeOtherClass(); } private SomeOtherClass _someField; protected void SomeMethod() { var foo = _someField.Bar(); } } 
+4
source share
1 answer

Having a protected or internal constructor like this is very often used for testing with Injection Dependency .

When you call the code normally, it simply creates an instance of SomeOtherClass , however when you run unit tests, you can pass its mocked version of SomeOtherClass that mimics it (say SomeOtherClass is your data level interface and SomeClass is your business logic level class that mocked the class fakes calls to the database and returns the results as if it were connected to the database)

 internal class UnitTest { [Fact] public TestDbInterface() { var someClass = new SomeClass(new MockedSomeOtherClass()) var result = someClass.SomeMethod() Assert.AreEqual("42", result); } } 

This allows you to perform unit testing without performing expensive operations, such as tuning to a known state and starting a full database server on a test computer, to test for tests that are not directed to classes for the data level.

+6
source

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


All Articles