I would like to unit test a method on a class I have made, but this method requires another method to be called first. Example:
// This would work MyClass myClass1 = new MyClass(mockDevice); myClass1.Run(myDatastructure); myClass1.Stop(); // This would throw an InvalidOperationException MyClass myClass2 = new MyClass(mockDevice); myClass2.Stop();
Run is starting an operation on a hardware device, and Stop is of course trying to stop that operation (sending a reset-command and starting a timeout-timer).
Anyway I would like to test various post-conditions of calling Stop, but I would like NOT to have to call Run, because I am testing Stop – not Run! I would like something like this:
MyClass myClass = new MyClass(mockDevice); myClass.Stop(); Assert.IsTrue(mockDevice.ResetCalled);
So far I only see one possible solution, and that is to create a TestableMyClass that inherits from MyClass, that makes it possible to set the right internal state of the MyClass instance before calling Stop. The problem with this solution is that I have to change my MyClass-implementation to have protected members instead of private members, and I don’t like the idea of having to change the implementation in order to test it!
Should I use this solution, is there an error in my design, or is there a smarter way of doing this?
As far as I see it, you are already testing
Stopin the two ways in which it can be used (with and without a running operation). As long as themockDeviceis doing its job, it seem to me that you’re testing it reasonably. Ideally you should be able to verify the commands sent to the device etc (which most mock frameworks will make simple).