Can I set private readonly instance variable? - c#

I'd like to know if somehow it is possible to set private readonly class variable via reflection or something?
Consider the following class:
public class TestSevice
{
private readonly someClassType m_variable;
public TestService()
{
m_variable = //call to some processing function
}
private static int CalculateStuff(int x, int y)
{
//some processing and return
}
}
I'm writing a unit test for private static method CalculateStuff(int x, int y), which I'm able to call via reflection:
PrivateType pt = new PrivateType(typeof(AvatarService));
int actialRes = (int)pt.InvokeStatic("CalculateStuff", parameters);
The problem is that, for my unit test to work, I don't want to set m_variable or set it to null on invoking the static function.
So, is it possible with a constructor is parameterless ctor to not set m_variable or custom set to to something in the unit test?
Edit:
Some details on //call to some processing function
Here, a call is made to start the receiver of message queue.
The class TestService is instantiated on the start of worker role, and hence the queue receiver is started in the ctor. The message queue receiver then calls a wrapper function in TestSevice class, which in turn calls CalculateStuff. And since I just want to test the core business logic, I don't want to start queue receiver(which imposes certain dependencies).

If you are trying to test a class by modifying its behavior you have already missed the point.
If there is a way that class can get into a certain test then that's how you should test it. With read only the only way to do that is through a constructor.
If the property is read only it suggests you only want to instantiate it once for a specific instance of that class and know it can't change. If that's the case the you shouldn't want to change it but possibly instantiate another instance.
If it needs to be changed before each call on calculate and you are in a situation where you think you need the function to be static, then you should probably have it as an extra parameter. This means it can longer be read only. Doing it this way would disconnect it from the state of a given instance but if you are trying/need to change the value it shouldn't be read only.

Apparently the answer is yes. https://stackoverflow.com/a/934942/2540156 But that doesn't really sound like your issue. It sounds like you want an alternate constructor to call during unit testing that will prevent the code from running that sets your variable. For that you'll have to make a change to your constructor.

Related

Initialize static class implicitly

is it possible to initialize a static class on app start up "automatically"?
By automatically I mean without the need of referencing a property.
The reason I want to be able to do this for is that I'd like to automatically theme an app on start up.
Here's a short snippet:
static class Settings{
private static Theme _defaultTheme;
public static Theme DefaultTheme{
get{
return _defaultTheme;
}
private set{
_defaultTheme = value;
ThemeManager.SetTheme(value);
}
}
static Settings(){
DefaultTheme = Themes.SomeTheme;
}
}
I know I can ( and that's how it is at the moment ) go with original getter/setter and call
ThemeManager.SetTheme( Settings.DefaultTheme );
in constructor of App ( it's WPF project ) and it'll do the job, however, at least from my point of view ( correct me if I'm mistaken please ) it'd make more sense for the default theme to apply without the need of explicitly stating it.
is it possible to initialize a static class on app start up "automatically"? By automatically I mean without the need of referencing a property.
The only way to guarantee that the static constructor will execute is to use the type in some form. It does not necessary need to be referencing a property (it could be constructing an instance, using a method, etc), but you do need to use the type. It is possible for the static constructor to never run otherwise.
Your current option, or a variation of it, seems like the best solution. You could change this to having a single call such as:
Settings.InstallDefaultTheme();
If you prefer, since the reference of Settings would force the static constructor to execute.

Securing property in a class library and requiring a only a certain method to set it

I have a class library (call it Lib1) that can be used in other project (call it Lib2).
Lib1 has a lot of static methods, but in order to be able to call them from Lib2 another method in Lib1: Configure() is required to run on the application start just once. This method should set a property (again, just once), and every time a static method from Lib1 is called, the property should be evaluated (lets say it needs to be equal to 5).
It is my understanding that the property needs to be static. However, the issue then is that this property can be hacked to be any value.
Instead the code that I require to run in Lib1:
Lib1.Configure() // sets property to 5
Someone could just write this:
(typeof(Lib1)).GetProperty("propertyName").SetValue((object)null, 5)
How can I assure that this hack would not fly?
I'm sure this is not the answer you are looking for, but it's the only correct answer: You cannot. Anything in the memory of a PC you do not control can be manipulated.
Create a static constructor and initialize your static read only field to the value (5 in your case) that you require.
public class YourClass{
private static readonly int yourCheckField;
static YourClass() { yourCheckField = 5 }
}

MemoryCache for Object

I have various function classes that preform long calculation. Currently every access to the result of the functions means recalculating the functions. That's why I want to incorporate MemoryCache in my solution. But the problem is that I need a ChangeMonitor Class that monitors the function class for changes. I have seen examples that monitor a file. My question is: do I need to write a custom ChangeMonitor or am I missing a simple solution?
An example just to be clear:
class MyFunction
{
//I want to monitor changes to these parameters
private int param1;
private int param2;
//This result should be cached
public int GetResult()
{
return param1 * param2;
}
};
You could use a Factory class to have a single class for access and creation of the MyFunction objects.
The Factory can then manage and synchronize the internal dictionary containing the previous calculations.
The MyFunction class needs to implement then IEquals and provide a hash function. Inside myClass you need to add private nullable int result.
Thanks for all the answers.
I realized that if I want to use the ChangeMonitor class I would have to extend it to monitor memory segments. The better solution in my case would be to alert the cache that a function result has changed. I have done this by adding a method 'Reset' to MyFunction class. Every time a parameter changes I just call the Reset function which will invalidate the cache.

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

Calling instance method from a constructor in C#

I have a rather lengthy constructor which is performing various initialisation work, and as such I wanted to factor out some of this work into some functions. This led to me wonder whether I should make the said functions instance or static methods. I understand the risk of calling a virtual function from a constructor but I also think there is something not right about calling an instance method on an object which is not 100% instantiated. Surely this is a contradiction in terms.
I'd be interested in peoples opinion on this matter. I also found that by using a static method to return an initialised variable I could make the member target read-only. Here's a simplified illustration of my scenario.
public class A
{
private readonly string _foo;
public A()
{
_foo = InitialiseFoo();
}
private static InitialiseFoo()
{
// Do stuff
return new string ("foo");
}
}
This is pretty normal to call instance method in a constructor, moreover method which doing Initialization. So basically this is a kind of Extract Method refactorig to reduce a constructor method body, so you are extracting part of initialization into a separate method and constructor is aware on saving of the input arguments, etc...
Regarding the static modifier.. sometimes (I believe when no other ways to refactor because this looks not good - from my point of view) you need to call a method to pass results in a base constructor so in this case you have to mark it as static to call in a static context in other cases leave it without the static modifier
public A()
: base(GetLogger())
{
}
private static ILog GetLogger() ...
I can understand the desire to only use static members in a constructor, because it DOES make the code more straightforward to use without having to track what has been initialized and what hasn't, but you're likely making things needlessly complicated for yourself. Calling an instance method in C# is fine as long as you have a good reason to do it. For instance, if you have a number of constructors that all perform some common tasks, creating a single member function to do the work is easier to maintain than copy-and-pasting the code for each constructor. You can also imagine a case where the method can be re-used outside of the constructor for something like reseting the class to the initialized state.
The static method, is fine, but will only work in the case where you are doing some isolated work and putting the result into a member variable. It provides a very clean, functional programming-like feel. If any of the work involves class state, however, it's going to get ugly.

Categories

Resources