views:

223

answers:

4

It is good practice to use the main method to test a java/.net class?

I've seen it reccommended in some text books, but to me it seems like using a unit testing framework would make more sense...

The main method gives you one point of entry to the class and you can test one aspect of the classes functionality. You could I guess test many but it doesn't seem to make sense as much as using Junit or Nunit.

+2  A: 

One obvious advantage seems to be that you can whitebox test the class. That is, you can test the internals of it (private methods for example). You can't do that with unit-tests, nor would you wan't that, they are primarily there to test the interface and the behavior from the users perspective.

Jasper Bekkers
A: 

The main method can be useful for certain situations, but using a debugger and then writing a unit test (to provide some insurance against regressions) is a more robust solution.

cynicalman
surely you should write your unit tests before you write your code... Thats what test driven development is all about :P
Omar Kooheji
I agree, but you could also write a unit test after a bug is discovered that illustrates the bug, then write the code to fix it.
tvanfosson
+1  A: 

I think it could be useful to develop integration tests that are invoked from a main method -- like a test runner -- that tests suites of integration tests. I wouldn't do unit testing this way as unit testing frameworks provide a much better mechanism to do this.

[EDIT] To clarify, I'm not suggesting that each class have static main method to be used for integration tests, but rather that you could write an integration test program with a static main method that would run your suite of integration tests.

tvanfosson
A: 

In Java it's accepted to have multiple main methods and use them for testing however .NET doesn't allow this, if you have two mains in the same program you will get compiler error CS0017, and tells you to Compile with /main to specify the type that contains the entry point.

I've got to say the Java way makes more sense to me.

Motti