开发者

Suggestion for JUnit testing

开发者 https://www.devze.com 2023-01-22 22:34 出处:网络
All, While writing a test method for method A (which has ma开发者_StackOverflow社区ny internal conditions), should I focus on testing a single condition each time? I am finding it difficult to struct

All,

While writing a test method for method A (which has ma开发者_StackOverflow社区ny internal conditions), should I focus on testing a single condition each time? I am finding it difficult to structure a test method for method A that would cover all the code path in method A.

Can anyone please suggest me how to go about writing a test method.?


Do not feel the need to have one-test-per-method. Keep your unit tests fine-grained, descriptive, and easy to understand. If that means multiple, similar tests all calling the same target method, then do it.

For that matter, try and avoid the habit of systematically writing a unit test for each method. Unit testing should be well thought-out, not habitual. They should describe the behaviour of classes, rather than of individual methods.


you should write a test for every execution path. For example, if you have

if (cond1 || cond2) {....}

you should test for cond1 and cond2. Separate test methods are fine and encouraged, if it makes sense. Its ok to have

testMyMethodCond1(){...}  

and

testMyMethodCond2(){...}

and whatever else you need. Also, when you say your method has 'many internal conditions', maybe you want to refactor your code so some of those conditions are handled in other, smaller methods, that are easier to test.


My preference is to have one failure point per JUnit test method. This means that I will have many JUnit test methods per target class method that I'm testing.

In your example, I may have testA1(), testA2(), testA3() all testing the same method (A). Each of these would test a different success or failure condition of method A.

If there are 8 paths through method A, then you need at least 8 test methods calling it and maybe some for error handling conditions.


First of all, you should consider breaking your method into several methods if it has more than one responsibility. Secondly, I would advice you to write multiple tests for each method. Each test should cover a specific path through the method under testing. Each test should also (of course) give the expected outcome depending on your test data.


Tests should be simpler, preferably much simpler, than the thing tested. Otherwise the error is more likely to be in your test. So it's much better to have a lot of small simple test methods that execute small parts of your method than one big clunky one. (You can use a code coverage tool like Cobertura to verify that you're covering all paths in your method.)

0

精彩评论

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