What are the good practice to test/inject private field in C# - c#

My apologies if this a duplicate. I have been given the task to add some coverage for the method and been told to mock the private List<string> property. My question is: Is there a way to test private fields?
The solution I found is adding new constructor just to inject this private list. I am not sure whether this is the right way, so any help will be highly appreciated.
public class Class1
{
public Class1(List<string> list)//This is just for Unit Testing
{
list1 = list;
}
private readonly InjectRepository _repository;
//
public Class1(InjectRepository repository)//This is the actual constructor
{
_repository = repository;
}
private List<string> list1 = new List<string>();
public void Do_Complex_Logic()
{
//list1 will be set with items in it
//Now list1 is passed to some other instance
}
}

The private logic of a class should be visible in the public expression of its behavior. In other words, the theory goes, there should be no need to test private fields at all.
There is no way to directly test private fields; they are private after all. If you really think that testing a private field is required, then I would suggest making it internal instead, and exposing it to your unit testing assemblies via the [InternalsVisibleTo] attribute.
That being said, there are frameworks that allow such things, such as TypeMock.

Don't test private fields or methods. Test the behaviour of a contract - public or internal methods.
That said, you can try:
Option A
Make private members internal and set InternalsVisibleTo attribute for the assembly under test.
Option B
Write a wrapper class that wraps you private fields/methods into public ones. This approach has a benefit that you don't need to make your private methods internal. The downside is that for every private method you will have a wrapper public method. So the amount of methods may double.

Adding to what womp & oleksii have already said -
The fact that you want/need to test a private method is a sign (smell?) that your design may be incorrect. This is one of the positive side-effects of TDD (and my personal favorite).
An example:
I don't fully know your domain here, but one simple change could be to, instead of Do_Complex_Logic taking no parameters, you could have it take and return a List<string>:
public List<string> Do_Complex_Logic( List<string> input )
I know - it's simple, but try deconstructing your class a bit and build it back with the tests in mind first.

I'm not disagreeing with the other answers; but in this case I think the most appropriate thing to do - given your code; is to change the signature of
'Do_Complex_Logic'
The real problem is that you are dealing with the 'state' of List1. If you pass List1 into Do_Complex_Logic - your problem is mostly solved. Your comment says that 'Do_Complex_Logic' is going to (presumably) do some work on List1 and then pass it into something else, right?
Make Do_Complex_Logic take a List and return a List. Now it's easy to test. Instead of depending on the state of List1 being setup correctly in your class, you can 'inject the dependency'.

How does the private field get prepared in the first place? If it is through interactions with the repository then you could possibly mock that object.
One way to do that is to interact with your repository through an interface (let's call it IInjectRepository rather than a concrete entity and then use something like Moq (or one of the many plethora of mocking frameworks out there) to populate your data via a mock'd repository as you setup your test. After you have called Do_Complex_Logic I assume you have a way of interrogating the entity so that you know it has done what you expected to. This way you can avoid/mitigate adding methods and classes that are for test only.

You could use reflection as mensioned in answer https://stackoverflow.com/a/3376157/1523402 of a related question.
I don't know if private accessors also work for private fields. But they help (at least) for private methods (see http://msdn.microsoft.com/en-us/library/ms184807%28v=vs.80%29.aspx).

Related

Nsubstitute testing if a private class's method was called

Don't have much experience with testing, trying to change that by testing libraries I've made recently.
Using nunit with nsubstitute for this.
So the situation I have is a class like this:
class MyClassToTest {
private ISomeOtherClass MyPrivateClass { get;set }
public MyClassToTest() {
MyPrivateClass = new SomeOtherClass();
}
public void DoSomething() {
MyPrivateClass.SayHello();
}
}
Now, a test for the DoSomething method would be to see if the method SayHello() was actually called on the ISomeOtherClass instance.
The problem is that it's private, when looking up the best way to test this, the only thing that came up was to make the property internal and set the InternalsVisibleToAttribute to the assembly the tests are in.
While this solution works and the external interface for my library is still ok, the correct accessor for this property in the context of the library would still be private.
The test I'd write is after making it interal:
public void MyTest() {
var objPrivateClass = Substitute.For<ISomeOtherClass>();
var obj = new MyClassToTest();
obj.MyPrivateClass = objPrivateClass;
obj.DoSomething();
objPrivateClass.Received().SayHello();
}
Is there a better way to test this without me having to modify my original code to make it testable?
It might be setting InternalsVisibleToAttribute and making the property internal is the correct thing here, but a couple of hours ago I didn't know about the existence of InternalsVisibleToAttribute so thought it best to ask :)
To answer the exact question, You can use reflection to reach private members, but that is a fragile and rather slow solution.
The best advice I can give you is that private things should stay private; test an object's behavior through its public interface. So if is too big and hard to test, just refactor it to be testable. Think of the Single Responsibility Principle and the Inversion of Control principles.
Edit 1.: You are probably looking for the concept of Dependency Injection. This should be alright most of the times; however when we talk about highly reusable libraries (you mentioned you are making a lib), other solutions may fit better for the users of your library (e.g. creating a Facade or rethinking your design).

Is this the correct architecture for a static class implementation?

I have a static class which will hold various utilities, for the sake of simplifying, I've added Customers and Orders:
public static MyUtilityClass()
{
public static readonly AnExpensiveObject ExpensiveObject = null;
public static Customers Customers;
public static Orders Orders;
static MyUtilityClass()
{
if (ExpensiveObject == null)
{
ExpensiveObject = //Expensive operation
}
}
}
In the above code, AnExpesiveObject ExpensiveObject is a property of the utility class that Customers and Orders will use.
Customers I've declared like this:
public class Customers
{
public void SomeMethod()
{
var x = MyUtilityClass.ExpensiveObject;
}
}
The theory if what I am trying to do:
Create a static class that has sub classes as properties so I can write neat code like:
Utilities.Customers.GetCustomerById(50);
Have these utility classes be able to access properties in the parent class, here since the parent class is static I'm just accessing it's properties directly without any inheritance model. Is this the right approach?
Also lastly Customers (The class) is coded non static, so do I have to create a new instance of it in MyUtilityClass() or because it is a static property of MyUtilityClass this is not needed?
At the risk of answering a question that is stated too broadly, I will give what I think is the correct, short answer: no, this is not the right way to do whatever it is you're trying to do.
Unfortunately, while you ask about inheritance, nothing in your code example shows any use of inheritance. So it's impossible to understand what you mean by that.
More problematic however, is the issue raised by your third point:
Also lastly Customers (The class) is coded non static, so do I have to create a new instance of it in MyUtilityClass() or because it is a static property of MyUtilityClass this is not needed?
The fact that you have to ask this question at all strongly suggests there's something fundamentally flawed with the design.
In particular, the question I would ask you is: what type of class is Customers? That is, does it make sense for your program to ever have more than one instance of it?
That question is an important one, as of the two possible answers, both lead to follow-up questions, both of which point to the proposed design as being wrong:
Possible answer #1: "no, there will only ever be one Customers object at a time". In that case, it makes more sense to implement the class as a singleton, which means the accessor should be e.g. an Instance property in the Customers class itself, not something in a separate "utility" class.
Possible answer #2: "yes, there can be multiple instances of the Customers object during the execution of this program". In that case, the question is raised as to which instance becomes the "special" instance in your "utilities" class and why? Furthermore, could there be more than one instance that would hold that special status? Why, or why not?
Hopefully it's the first answer above that is correct, in which case the path is clear: use the singleton pattern rather than this catch-all "utility" class.
If it's the second answer above that is correct, then I can say with reasonable confidence your proposed design is incorrect. Unfortunately, to say what design would be correct would be much harder, and would require far more detail from you, making the question itself far too broad for StackOverflow.
It works as I expected, and is easy to reuse, so I'll answer the question.

Mocking a private field

I know a similar question has been asked but I have not found a clear solution. I'm trying to mock a private field from a large class. The private field gets instantiated in some earlier method and I'm trying to unit test a latter method which references the field.
So I have an earlier method in my class:
public bool validateAll(ref DataEntry[] oEntries, string sMediaPlanId, ITemplateGenerator oTempGen)
{
...
// private field that I am trying to mock
this._sMediaPlanObjective = (MPWrapper.Instance).getMediaPlanObjective(sMediaPlanId);
...
}
And I'm trying to Unit test a method that references the private field:
public bool validateFlightObjective(ref MPDataEntry oEntry)
{
...
string entryFlightObjective = oEntry.getFlightObjective();
string mediaPlanObjective = this._sMediaPlanObjective;
if (entryFlightObjective != mediaPlanObjective)
{
return false;
}
...
return true;
}
Given that I have a large class and this is just one method I want to test, is there a possible way to just mock this private field? Am I missing something basic or should I consider some other approach?
You can't mock anything that's private, static, or essentially - non overridable (this comes as a free mocking libraries limitation).
What you usually do in such situations (when it appears that private member has to be tested), is extracting your private member to a separate class and inject it to tested class as a dependency.
In your case, you actually need to extract code that creates _sMediaPlanObjective, which is this line:
this._sMediaPlanObjective =
(MPWrapper.Instance).getMediaPlanObjective(sMediaPlanId);
Object that provides getMediaPlanObjective method should be injected to your tested class. If you do so, you can simply mock that object and tell it to return mocked version of _sMediaPlanObjective.
You can use JustMock framework.
For example:
double value = 0;
var fakeFilterSetHelper = Mock.Create<FilterSetHelper>(Behavior.CallOriginal);
Mock.NonPublic.Arrange<double>(fakeFilterSetHelper, memberName: "GetPriceRangeFromSession").Returns(value);
There is no reason to have any kind of tests on private fields.
using an object you can reference to the public methods as the object API.
the object itself can have it's changing state according to the operation you perform on it - but it will be reflected in other public methods / access to DAL (DB / Registry / File/ any other resource that is not in memory)
So in your case you can have a unit tests like that:
call the method that initializes the private field as you expect it to and -
Call validateFlightObjective with a parameter that you know that have to return false according to the _sMediaPlanObjective "wanted to be state", and verify that the result is false.
Call validateFlightObjective with a parameter that you know that have to return true according to the _sMediaPlanObjective "wanted to be state", and verify that the result is true.
If you see that it is hard to test this object, then that might be a "smell" - maybe you have more than one responsibility there and you should start refactoring and split the class to smaller classes which will be easier to test
That it a bit long but i hope it was helpful

Should a c# class generate instances of itself?

I have a class that defines a CallRate type. I need to add the ability to create multiple instances of my class by reading the data from a file.
I added a static method to my class CallRate that returns a List<CallRate>. Is it ok for a class to generate new instances of itself by calling one of its own constructors? It works, I just wonder if it's the proper thing to do.
List<CallRates> cr = CallRates.ProcessCallsFile(file);
It is perfectly fine to get object(s) of its own from the static method.
e.g.
One of the dot net libraries does the same thing as you did,
XmlReadrer reader = XmlReader.Create(filepathString);
Sure that's fine, even encouraged in some instances. There are several design patterns that deal with object creation, and a few of them do just what you're describing.
I often use this pattern when I need to check the validity of parameters. It is strongly discouraged to throw an exception from a constructor. It's not so bad from a factory method, or you can choose to return null.
Seems fine to me. In other languages you would probably write a function, but in a language like C#, static methods take up that role.
It is ok. What you just created is something like a simple factory method. You have a static method that creates a valid instance of a type. Actually your method doesn't even have to be static and you still have a valid code. There is a design pattern (Prototype) that creates a new valid object from an existing object. See details at http://www.dofactory.com/Patterns/PatternPrototype.aspx.
Sure, for simple parsing (or similar) scenarios - I actually prefer the factory method be part of the class. Yes - it does break SRP, but it fulfills KISS - so I call it a net win. For larger apps, or more complicated parsing routines - it makes more sense to have it be an external factory class.
For your particular case, I'd probably prefer a method that took in an IEnumerable<string> instead of a filename - that'd still give you the parsing logic, but allow easy unit tests and "reuse". The caller can wrap the file into an IEnumerable easily enough.
Factory methods are often a good design. When I write them in C#, I call them 'New', so that:
new MyClass()
becomes
MyClass.New()
Trivially it's implemented like this:
class MyClass
{
public static MyClass New()
{
return new MyClass();
}
}
Mostly I do this when there are additional conditions about whether to actually create the class or just return null, or whether to return MyClass or something derived from it.
I sometimes use public static methods as an alternative to constructor overloading.
Especially in situations where it is not nice to rely on parameter types alone to indicate what kind of object construction is intended.
I'm a fan of having static methods return instances, as suggested plenty of times, above.
#Paul: don't forget to tick the comment above, which you find is the best answer.
Just like to point out
"generate new instances of itself by calling one of its own constructors"
It is not from the constructor, it is from the static method.
I generally use this when I need instant implementations of a class. For example
public class Car
{
public static Car RedExpensiveCar = new Car("Red", 250000);
public Car()
{
}
public Car(string color, int price)
{
Color = color;
Price = price;
}
public string Color { get; set; }
public int Price { get; set; }
}
And with this, I don't need to remember or write constructor parameters in my code.
Car car = Car.RedExpensiveCar;
It's perfectly acceptable to do this. When I do, I typically make the real constructors for the class private so that it's clear that the only way to construct instances is through the static method.
This is very useful in cases where "construction" may not always return a new instance. For example, you may want to return a previously cached object instead.

Unit Testing with the Mediator Pattern - All Private to Public

I am using the mediator pattern to facilitate unit testing of GUI objects.
psudo code Example:
Class MyGuiClass
{
//... Declare and initialize mediator to be a MyMediator
private void On_SomeButtonPressed()
{
mediator.SomeButtonWasPressed();
}
}
Class MyMeditator
{
public void On_SomeButtonPressed()
{
//.. Do something now that the button was pressed
}
}
This is nice because I can now unit test what happens when SomeButton is pressed without having to create a Window.
My concern is that I have taken a method that was private and made it public for any one who makes a Mediator to call. Past times I have done this it did not bother me because I did not have many methods that I had to make public.
I am currently refactoring a very large class to use this pattern and I am wondering if there is someway I can control the visibility of who can make a MyMediator or which classes some of the methods are public for. (This may not be possible or even needed, but I thought I would ask.)
(I am using C# 3.0 with .NET 3.5 SP1)
I think it doesn't matter.. Who has an instance of the mediator, other than the gui? If someone does, is it going to call the method? If it does, does it matter? Will it be hard to notice, diagnose and fix the bug?
I think you can achieve what you are looking for with events though:
e.g.
/* in the gui class (view) */
public event EventHandler OnButtonClicked;
/* in the mediator */
public MyMediator(MyView view)
{
view.OnButtonClicked += HandleButtonClicked;
}
private void HandleButtonClicked(object sender, EventArgs e)
{
}
Not sure about c#, but in java you can declare something as package-level access (in java by omitting the access specifier). What I do is create a separate test hierarchy that parallels my package structure, so to test class com.a.b.c.MyClass, I'll have a test class com.a.b.c.MyClassTest, which can then legally access the package-access methods in MyClass.
I don't so much like the idea of making everything public not only because of access issues, but because it clutters up the interface - I'd rather the public interface of the class express what it does, not how it does it, which is often where I end up if I expose methods I'd prefer to be private.
The point is that you'd like the public interface of a class to show that class's public 'API', so in making private methods public you are making the class more confusing and less 'clean'?
A few things you can do:
1) think through what actually is the 'public face' of your mediator (or humble object) class and happily make those methods public. Even if they are only used within the assembly - not part of the assembly's public face - that's okay because notice that your mediator class itself is not declared public. So even its public methods are still internal to the assembly.
2) You can fudge the privates by using internal for private (and then set the assembly's InternalsVisibleTo attribute if your test classes are in a separate assembly).
3) Take the 'black box' approach to unit testing whereby in principle you never need to test the privates because they get tested via their use when called from the public methods.

Categories

Resources