Flair
Flair

Reputation: 2965

Can I set private readonly instance variable?

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).

Upvotes: 1

Views: 2023

Answers (2)

Adam47
Adam47

Reputation: 196

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.

Upvotes: 0

tam
tam

Reputation: 1583

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.

Upvotes: 1

Related Questions