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.
Related
Currently the JUnit5 Framework works with Inversion of Control. I.e. you annotate a test method with #Test and then JUnit scans your classpath (in the simplest case)
Now is there a way for me to be in charge of calling the test cases through JUnit APIs? Maybe by hooking my test implementations to some test registry provided by JUnit?
I'm pretty new to JUnit - how did older versions go about this?
The reason I'm asking is that normally to execute my test cases, I'd have to run something along the lines of
java -jar junit-platform-standalone.jar --class-path target --scan-class-path
on the command line. My situation requires me to run the test cases through by executing one of my own classes, like that e.g.
java /com/example/MyTestCassesLauncher
EDIT: to clarify, I need one of my own classes to be hosting/launching my test cases, something like this:
// Maybe this needs to extend one of JUnit's launchers?
public class MyTestCassesLauncher {
public static void main(String[] args) {
JUnitLauncher.launchTests(new MyTestClass());
}
}
where JUnitLauncher.launchTests is some kind of API provided by the platform. I'm not looking for a method with that exact same signature but a mechanism that would allow me to ultimately call my own MyTestClassesLauncher class to run the tests.
Thanks in advance.
Not sure what you arÄ™ actually trying to achieve but in Junit5 to change behaviour of your tests you can use Extensions mechanism, similar to Junit4 RunWith but more powerful
Such custom extension can provide some additional logic like in this logging example
public class LoggingExtension implements
TestInstancePostProcessor {
#Override
public void postProcessTestInstance(Object testInstance,
ExtensionContext context) throws Exception {
Logger logger = LogManager.getLogger(testInstance.getClass());
testInstance.getClass()
.getMethod("setLogger", Logger.class)
.invoke(testInstance, logger);
}
}
The way Junit controls it's flow is Junit problem - you should not modify framework but extend it
I ran into some trouble testing a Spring app. The current approach in my team is to write scenarios in Gherkin and have Serenity provide its pretty reports.
A new component in the app will need a lot of test cases. The requirements will be provided in a few 'parsable' excel files so I thought it would be neat to just use them directly, row by row, in a Junit parametrized test. Another option would be to write a bloated Gherkin feature and tediously compose each example manually.
So I thought of something like that:
#RunWith(Parameterized.class)
private static class Tests {
#Parameterized.Parameters(name = "...") // name with the params
public static Collection params() {
// parse excel here or use some other class to do it
}
#Test
public void test() {
/* do the actual test - it involves sending and receiving some JSON objects */
}
}
This works smoothly but I ran into trouble trying to use
#RunWith(SerenityRunner.class)
The problem is that Junit does not support multiple runners. A solution I found is to make a nested class and annotate each with a different runner, but I don't know how to make it work (which runner should be on the outside, where do I actually run the tests, an so on).
Any thoughts?
Actually Serenity provides another runner - SerenityParameterizedRunner which seems to have the same features as JUnit's Parameterized.
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
}
I have a class that takes in a single file, finds the file related to it, and opens it. Something along the lines of
class DummyFileClass
{
private File fileOne;
private File fileTwo;
public DummyFileClass(File fileOne)
{
this.fileOne = fileOne;
fileTwo = findRelatedFile(fileOne)
}
public void someMethod()
{
// Do something with files one and two
}
}
In my unit test, I want to be able to to test someMethod() without having to have physical files sitting somewhere. I can mock fileOne, and pass it to the constructor, but since fileTwo is being calculated in the constructor, I don't have control of this.
I could mock the method findRelatedFile() - but is this the best practice? Looking for the best design rather than a pragmatic workaround here. I'm fairly new to mocking frameworks.
In this sort of situation, I would use physical files for testing the component and not rely on a mocking framework. As fge mentions it may be easier plus you don't have to worry about any incorrect assumptions you may make of your mock.
For instance, if you rely upon File#listFiles() you may have your mock return a fixed list of Files, however, the order they are returned in is not guaranteed - a fact you may only discover when you run your code on a different platform.
I would consider using JUnit's TemporaryFolder rule to help you set up the file and directory structure you need for your test, e.g.:
public class DummyFileClassTest {
#Rule
public TemporaryFolder folder = new TemporaryFolder();
#Test
public void someMethod() {
// given
final File file1 = folder.newFile("myfile1.txt");
final File file2 = folder.newFile("myfile2.txt");
... etc...
}
}
The rule should clean up any created files and directories when the test completes.
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