Click here to Skip to main content
15,947,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a test project for unit testing the methods in my c# project and various test methods in it. In actual method, there are global class level variables used whose values are set from constructor or other methods. So when actual project runs, the variables have value when referenced in method. Now when I run test for test methods it directly calls the actual method with supplied parameters, but then it will not get the value of global variables, instead getting null.

So my question is that is it possible to unit such kind of methods, or only standalone methods can be unit tested? If yes, then how?

Thanks in advance. :)
Updated 2-May-13 1:34am

1 solution

This is a classic case. You can make the global dependent variables in a config (or some container class) which implements an interface. Now in the live example implement your interface with a config reader class and your methods should read these values from the interface only.

You can create a property (or setter method) so that you can inject a test implementation

Now while testing you can create a test implementation and set the property with the implementation and then your methods should work the same way.

Here is some example code:

public interface IPlayer
        string Name { get; }

public class Player : IPlayer // this class is your live class -- use a similar one in your test
     private InputManager inputManager;

     public Player(string name)
         Name = name; // dependency inject or read from config

let me know if you need more code to understand
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900