简体   繁体   中英

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?

PS 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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM