njvb
njvb

Reputation: 1377

Test methods in the same class as main with JUnit

OK, so before we start let me state that I have been googling and searching for an answer to my question for quite a while now and haven't been able to find a suitable one (the keywords are tricky since I keep getting unrelated posts and sites as results).

Now, moving on I have a Java class that contains a my main method and a number of other functions. I want to test these functions using JUnit but I can't instantiate a class that has main in it, if I simply try to call the function I get an error saying the function is outside the namespace even though both files are in the same package, and I get an error trying to import the file.

Is there anyway to test these functions using JUnit?

P.S. Yes I know that you can put them in a new class, but I don't think it is overkill to create a new class just for testing or to put in 2 functions that are for parsing user input, and there is still the issue of testing the main function itself (and it is not uncommon to write a main method just for testing).


So this is what happened. Since I don't use Java very often I ended up creating private data members in the class but treated them as I would globals in a C++ program. In consequence I initialized them in main and didn't think of making a constructor and hence the problem with instantiating the class. When that didn't work I tried the . form but since the methods referenced the private data members I would get an error without instantiating the class. Thanks to the guys that noticed the constructor thing.

Upvotes: 1

Views: 2588

Answers (3)

Alvin
Alvin

Reputation: 10458

Just a thought, did you declare constructors as private in the class with main method? It will help a lot if you can post some code snippet and exact error message you're getting.

Upvotes: 0

Victor Sorokin
Victor Sorokin

Reputation: 11996

Very strange. I just wrote SomeClass with main inside and it's perfectly testable by SomeClassTest class.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

You absolutely can create an instance of a class which contains a main method, so long as it has an accessible constructor of course.

Likewise you absolutely can call a static method directly, using MyClassName.myMethodName.

Having a main method in a class makes absolutely no difference to it in terms of the Java language itself - so you can test it just as you would any other class.

Upvotes: 5

Related Questions