How to sequentially execute 2 Java classes via mvn

2019-03-03 15:18发布

问题:

I have 2 Java classes which have a symbiotic relationship.

Class 1 produces some output files and Class 2 consumes the output of class 1 and validates it. Both of these classes take input from the commandline. This project is maven based.

Given this symbiotic nature, I am unsure how to "connect them"?

My thinking was, to write another Java class which takes in command line inputs and calls the 2 classes. However there is another uncertainty here, how could I run class 1 (in order to produce the output files) so then I can have class 2 to validate it. Perhaps Junit @Before or some annotation? I really am unsure how to proceed. I hope I am making sense here.

Any help or suggestions would be much appreciated.

回答1:

Execute the main() method of your class under test from within a JUnit method.

public class Class2 {
  @Before
  public void produceOutputFiles() {
      Class1.main(new String[] { "these", "are", "commandline", "arguments"});
  }

  @Test
  public void validateClass1Output() {
      //read in the files and validate the output
  }
}

Invoking Class1 via Process.exec() is an option with many downsides. It is much simpler to keep both the test and the tested code within the same JVM.