简体   繁体   中英

How do you unit test main method in Java?

This is my class with main function. Here I initialize a spring bean which has camel route in it. I do not want to test any other classes being referred in this code but I just want to increate code coverage of this main class. How do I mock and test this class?

import org.apache.camel.main.Main;
public class ABC{
public static void main(String[] args) {

        Main main = new Main();
        MyCamelRoute myCamelRoute = SpringUtil.getBean(MyCamelRoute.class);
        main.addRouteBuilder(myCamelRoute);

        Thread t = new Thread(() -> {
            try {
                main.run();
            } catch (Exception e) {
                _logger.error("Unable to add route", e);
            }
        }, "started route");

        t.start();  
    }
}

As you're writing of "mocks" I assume you intend to write a unit test.

ONE: Either you test a class or you mock it. You use mocks to make your test independent of the behaviour (and thus possible bugs) of other units (the "dependencies" of your "system under test" (SUT)).

TWO: You do not write tests to increase code coverage. You write tests to enforce requirements of the API contract.

THREE: To test your main method: call it! You can put in arguments and see if the return value matches your expectations.

FOUR: The problem here might be that you've got static dependencies you cannot control. Spring allows you to configure mocks for bean injection. Can't tell you details right now but I am sure you can find out, it should be something like @Configuration annotated classes or test specific versions of them.

But: your test has no control whatsoever over the main object. And sincerely, I would guess that actually you intend to test the Main class. Also you might want to inject the Main instance via Spring means.

FIVE : I am not sure wether it is a good idea to involve multi threading in unit tests as it means your test cannot control the environment of your sut. If you do not know where your test starts, you cannot decide if where it ends up is correct or not.

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