views:

220

answers:

4

What to test in unit testing, a method or a scenario?

If test each method then minimal test case setup is required.

If test a method which calls other methods then setup required for the test case is huge. If unit-tests for the individual methods are already there then why to write for this method which is using them?

But then it also have little bit of functionality which should be tested. Also the code coverge tool will complain about coverage percentage.

Please provide your practical inputs.

A: 

Duplicate: http://stackoverflow.com/questions/517977/what-do-you-test-with-your-unit-tests

Tomas Lycken
Its not the duplicate of that question, its not answering what I want. Please read the question. Maybe the subject line need to be rephrased.
Bhushan
+3  A: 

If test a method which calls other methods then setup required for the test case is huge. If unit-tests for the individual methods are already there then why to write for this method which is using them?

Because that method may call the underlying methods with the wrong parameter, or in a wrong sequence, or do the wrong thing with the return values.

In my experience, the potential for errors in self-contained methods is usually rather small compared to the interaction between them and such "glue code".

"Classic" unit tests, where you completely test each class's behaviour in isolation are a nice concept, but in reality, this scenario is not all that common or useful. It depends on how much care was taken to design the code for modularity and (implied in that) testability, but it's never possible to achieve for everything.

Michael Borgwardt
+2  A: 

You unit-test a method, with one test case per possible execution path.

The typical structure of an unit test is Arrange-Act-assert (triple A's):

  • Arrange - create the environment for the case you want to test (this can be done in the Suite setup or in the TestCase, or both)
  • Act - the test case invokes the method under test
  • Assert - to verify the method under test did what it is supposed to do

Excessive setup should be an indication that you should look at your design, for instance, your class could be too big, or doing too many things. Excessive setup is an anti-pattern.

You can use mock objects to isolate the class you're testing.

philippe
+2  A: 

The number-one rule of unit-testing is:

Only test one thing at once!

This means: you don't even test a method, you test a single aspect of a method under a single condition. So you come up with several tests for the same method.

Isolation is a key for good unit tests. You need to mock your dependencies (eg. using RhinoMocks). At the beginning it looks more complex, but in the long run it is much easier to manage and maintain. Test only a small amount of code in a test, make you test as trivial as possible and you will have maintainable tests.

Stefan Steinegger