I\'ve got a class that has a private member that has for type System.Windows.Forms.Timer. There\'s also a private method that is being called every time my time
Is it worth testing the method? (since it's private)
Your purpose is to decide whether your code works or not. Even it's a private method, it should generate an output that can be reached by the public interface. You should design your class in a way that the user can know if it's working or not.
Also when you are unit testing, the callback assigned to Elapsed event of the timer is reachable if you can mock the timer.
How can I test it? (I know I can have my test class inheriting the class I want to test...)
You can use an adapter class here. First you have to define an abstraction since Timer class doesn't offer one.
public interface ITimer
{
void Start();
void Stop();
double Interval { get; set; }
event ElapsedEventHandler Elapsed;
//and other members you need
}
Then you can implement this interface in an adapter class, just inheriting from the Timer class.
public class TimerAdaper : Timer, ITimer { }
You should inject your abstraction in the constructor(or as a property) so you can mock it in your tests.
public class MyClass
{
private readonly ITimer _timer;
public MyClass(ITimer timer)
{
_timer = timer
}
}
Should I be mocking my timer? Because if I have to test a class that uses an internal timer, my tests may take a lot of time to complete, right?
Of course you should be mocking your timer. Your unit tests cannot depend on system time. You should raise events by mocking and see how your code behaves.