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.
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.
Related
I've only ever used Cucumber in conjunction with Selenium to test websites.
I'm now trying to write a feature file to test a class but I'm not sure how, I have my test step running which calls the main method passing in some arguments. The main method does some things with the arguments and prints them to the console. Is it possible to read the console output to a string so I can assert it matches what I expect?
#Given("I pass the arguments {string} to the generator")
public void i_pass_the_arguments(String string) {
String[] args = string.split(" ");
new Generate();
Generate.main(args);
}
If you are testing a specific class only, I'd recommend using unit tests for that, for example using JUnit. They will have less overhead and be easier to run and maintain.
I have multiple class and multiple test. but when i used:
public class ParallelComputerExample {
#Test
public void runAllTests() {
Class<?>[] classes = { Class1.class, Class2.class, Class3.class };
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
}
It run all #Test in the same time. I want it just create max 5 instance ?
Simple answer: the existing structure doesn't support that. JUnit doesn't have a way to run tests in parallel ... but under such constraints as you are asking for.
Thus: you most likely have to build something like that your own.
The good thing: that should be rather easy. You see, that ParallelComputer object you are using there is simply extending the base Computer class.
In that sense: go, and have a look into the source code of those two classes (you know, it is open source) - and then build your own extension of that Computer class that runs jobs in parallel, but using a limited thread pool for example.
I am currently writing JUnit test cases using the Selenium-RC API. I am writing my scripts like:
//example JUnit test case
public class myScripts extends SeleneseTestCase {
public void setUp() throws Exception {
SeleniumServer newSelServ = new SeleniumServer();
newSelServ.start();
setUp("https://mySite.com", "*firefox");
}
public void insert_Test_Name throws Exception {
//write test code here
}
}
And for each test, I have a new JUnit file. Now, since the beginning of my JUnit files will all basically be the same, just with minor variations towards the end, I was thinking about creating a pre-formatted Java template to write create a file with the redundant code already written. However, I can't find any information on whether this is possible. Does Eclipse allow you to create file templates for certain packages?
Create a super class to add all the common code. Creating template is really bad because of the fact you are duplicating the code at the end of the day.
class Super extends SeleneseTestCase{
// Add all common code
}
class Test1 extends Super{
// only special test case logic
}
Also I would suggest not to create SeleniumServer instance for each test case, It will reduce overall performance of the test suite. You can reuse object as long as you are running test sequentially.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a Java program which reads the contents of a file containing a list of numbers, picks out numbers which have been duplicated and writes them to the console.cant figure out where to put them or what they should look like.
import java.util.;
import java.io.;
public class ReadAFile {
public static void main(String[] args) {
String list[] = new String[];
FileInputStream fstream=new FileInputStream("C:/Users/Kevin/Desktop/testfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br=new BufferedReader(new InputStreamReader(fstream));
String str,str1;
int i=0;
while((str=br.readLine())!=null){
i++;
str1=Integer.toString(i);
if(lines.containsValue(str)){
System.out.println(str);
}
in.close();
}
}
you need to think of a test-case, write a test-class, and put it under /src/test/java directory.
Then you need to write some methods inside test-class(separate method for a testcase is common way), annotate that method with #Test annotation and run maven
You can look at this tutorial here!, it very thorough providing details about how to run Unit tests in Eclipse and making use of EasyMock.
First step would be to organize your code in units so that each unit can be tested. In Java world, this unit would be a method in your class. So first step, write your code in a method other than 'main'.
Next, you write a program which tests the method you wrote. Basic structure of such a program would be
1) Do anything which is required to run the method under test.
2) Run the method
3) Observe the output to verify if it produced correct results.
JUnit is a Java library which makes it easy for your write such tests by providing some pre-canned methods.
You have the basics now, rest, as they say, can be googled.
Really straightforward tutorial is here from mkyong it worked really well for me when I started with unit tests. Also some mocking for the Input Output manipulation will be handy.
Unit tests in a maven project usually are located in a separated source folder /source/test/java. Maven automatically executes all tests found at this location.
To test your class you would have to refactor it so you can set the path to the input file to an test file that you may place in /source/test/resources for instance. At least if you want to write an integration test that verifies the reading of the input file.
The processing logic that identifies and prints duplicated entries may be tested via a "real" unit test that somehow mocks the BufferedReader and provides some test data without reading it from a file. Here easymock may be one library you can use.
To simplify the testing of your class your may put all your logic in a non-static method and call it from your main method by creating an instance of the class itself.
public class ReadAFile {
public static void main(String[] args) {
ReadAFile instance = new ReadAFile();
instance.readAFile(args[0]);
}
public void readAFile(String fileToRead) {
HashMap<String,String> lines=new HashMap<String,String>();
...
}
}
As you already has included junit in your project, you have to think in the following structure for unit testing.
You will have for each class you want to test, a correlative class to test it, so MathTest will unit test Math class
Then, imagine you modify your code to have 2 methods, one for read a file, one to parse the InputStream and one to showResults.
Here is an Interface I would use, but take it just to know the method declaration.
public interface MyCodeToBeTested {
List<String> parseFile(final String path);
void processLines(List<String>);
}
Imagine you implement this interface with a class named ImplementedClass.
So you can have a Junit class which test each of the methods looking for fails.
import junit.framework.Assert;
import org.junit.Test;
public class Tester {
#Test
public void testReadFile() {
ImplementedClass myclass = new ImplementedClass();
List<String> lines = myclass.parseFile("mytestfile1.txt");
Assert.assertEquals(3, lines.size());
Assert.assertEquals("this is the first line of the file", lines.get(0));
}
}
With this test you check that parsing a file works fine, one time you are confident with your read file though unit testing, you can move to test the processLines method without taking care of the file.
#Test
public void testProcess() {
ImplementedClass myclass = new ImplementedClass();
List<String> lines = initializeLines();//initialize your lines
myclass.processLines(lines);
//Assert here myclass results
}
The selenium tests I'm gonna be doing are basically based on three main steps, with different parameters. These parameters are passed in from a text file to the test. this allows easy completion of a test such as create three of "X" without writing the code to do the create three times in one test.
Imagine i have a test involving creating two of "X" and one of "Y". CreateX and CreateY are already defined in separate tests. Is there a nice way of calling the code contained in createX and createY from say, Test1?
I tried creating a class with the creates as seperate methods, but got errors on all the selenium.-anything-, ie every damn line. it goes away if i extend seleneseTestCase, but it seems that my other test classes wont import from a class that extends seleneseTestCase. I'm probably doing something idiotic but i might as well ask!
EDIT:
well for example, its gonna be the same setUp method for every test, so id like to only write that once... instead of a few hundred times...
public void ready() throws Exception
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://localhost:9443/");
selenium.start();
selenium.setSpeed("1000");
selenium.setTimeout("999999");
selenium.windowMaximize();
}
thats gonna be used EVERYWHERE.
its in a class called reuseable. Id like to just call reuseable.ready(); from the tests SetUp... but it wont let me....
public class ExampleTest {
#Before
public void setup() {
System.out.println("setup");
}
public void someSharedFunction() {
System.out.println("shared function");
}
#Test
public void test1() {
System.out.println("test1");
someSharedFunction();
}
#Test
public void test2() {
System.out.println("test2");
someSharedFunction();
}
}
The contents of the function after the #Before annotation is what will be executed before every test. someSharedFunction() is an example of a 'reusable' function. The code above will output the following:
setup
test1
shared function
setup
test2
shared function
I would recommend using JUnit and trying out some of the tutorials on junit.org. The problem you have described can be fixed using the #Before annotation on a method that performs this setup in a super class of your tests