开发者

Unit testing chained private methods in C#

My problem is that I have public method in my class and it is calling a private method. The private method is calling another private method and so on 开发者_Go百科with 4 chained private methods. I know that I should write unit tests only for public methods. In my case I will have full code coverage, because all private methods are called from the public method. But in case something goes wrong my unit test won't know exactly which method screwed it up. I know that I should try to move some of my methods in separate classes, so that I can test them but this means that I should make 4 different classes with only one method in each.

So is there a way to test each of these private methods, or I just should use the integrated feature in Visual Studio for testing private methods?


You are already testing the private methods by calling the public one. You test the input and output of the public method - which relies on the private ones, hence all are being tested. Any problems that occur will result in an exception which (upon checking the stack trace) will inform you which method (private or otherwise) is causing the problem.

Private members are just that, private. They shouldn't be exposed to the outside since they're only concerned with the inner workings of the object, hence unit tests should (and can only) test the public ones, which is what you're already doing.


You should concentrate on testing observable behaviour, which means testing expected consequences of calling public methods. If the private methods are performing a lot of work then consider moving them into objects injected into the object under test, if not then if something goes wrong it shouldn't be too hard to debug :)


Stoimen,

I agree with you.

I read many of forums saying that PRIVET methods should not being tested because it is within other public tests. But the main reason is to isolate and make it simple to build blocks and create isolated levels of test. Not for you but for others that do not agree with my opinion, here is one simple example: Public method BuildCar (sizeOfChassi, typeOfBody, Color) { Call private MakeChassi (sizeOfChassi) Call private MakeBody (typeOfBody) Call private Paint (Color) } In this scenario, I don’t want to be public MakeChassi, MakeBody and Paint because I just build and sell cars, but I want to thoroughly test my factory. If I just use the public method, I’ll need to create a lot of testing variations and of course I have a risk to forget some. Just testing the small parts (the main reason of UNIT TESTs), I’m pretty sure that they are working. Other thing is inside the class I could create another public method to use those privates, without need to re-write tests variants.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜