Dynamic method calling of a JUNIT class - java

I am having a excel sheet having testcases name and some values related to it
eg: TestCase2 Value2, TestCase1 Value1.
I have a Junit class having test methods(TestCase1(), TestCase2()) as the same name I have in excel sheet
So when I run my Junit class I want the test methods to execute serially the way they are mentioned in excel file as in this case testcase2 should execute before testcase1.

Method 1:
Use Excel to construct and launch command lines, with Excel/windows capabilities (VBscript, ...).
To launch junit tests:
java org.junit.runner.JUnitCore [test class name]
see that:
How to run JUnit test cases from the command line
Note that you can launch a class, not a particular method.
For particular method, see that: Run single test from a JUnit class using command-line
For the order of methods, see below.
But, how you get and exploit results is another thing.
Method 2 (prefered): Control everything from Java:
Read excel file, with proper library:
How to read and write excel file in java
or, change it to csv, or OpenOffice (odf), and read with other libraries.
Iterate, and launch each method by its name by reflexivity:
getMethod and Invoke.
See that: How do I invoke a Java method when given the method name as a string?
Order of tests:
Set this before the class:
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
Then your tests will be executed in lexical order
Hope it helps !

Related

How can I pass a dynamic parameter-that I will create with some random library- in testNg xml?

I want to pass a dynamic parameter to a test case from testng xml, my parameter is something like:
String dynamicParameter=generateRandomStringForMail();
Here is my testcase:
#Test()
public void customerCreatorAllProducts () throws Exception {
setup();
Functions.pages.LoginPage login = PageFactory.initElements(driver, Functions.pages.LoginPage.class);
login.navigateRegisterPage().createFixedPasswordCustomerRequiredFields(dynamicParameter);
}
I will be using this parameter in other cases as well, how can i do this from testng.xml or with something else?
I am not familiar with testing.xml, but Mockito immediately comes to mind for this: http://mockito.org.
add Mockito to your project (e.g. through the build.gradle page)
add the import to your test file:
import static org.mockito.Mockito.*;
within your test class, create a mock of the class which has the generateRandomStringForMail() method. In my current project, I have
DefaultFileService mockFileService = mock(DefaultFileService.class);
define what you want the method to return under these test conditions, e.g.
when(mockFileService.generateRandomFileName()).thenReturn("fileName");
Whenever your tests need to use the result of the method in question, you can use "fileName", because you have told the test environment to give this response. My project has a method to update the image file associated with an inventory item, which process includes using the DefaultFileService to generate a random file name, then passing the image file and the new file name to the DefaultFileService to save the file in the system. My test code can't see or guess what file name would actually be produced, but my 'when' line above has resolved that problem for the purposes of testing my QuiltController class:
quiltController.update(data, mockFile);
verify(mockFileService).save(mockFile, "fileName"); // confirms the save() method was called with the expected parameters
It feels pretty similar to what you are trying to do, so hopefully that helps you proceed if you do want to explore Mockito. Don't be surprised if you need to refactor some of your work to make it more testable. I did, and have better code as a result. Give it a go :)

JUnit - Run specific tests using JUnitCore

I have a couple of classes which contain Tests.
I have a main method that uses JUnitCore in order to run all tests.
What can I do in order to run specific tests in each class?
Currently I use something like this to run all my tests :
Result result = JUnitCore.runClasses(TestJunit.class, TestJunit2.class);
Maybe there is a possibility to categorize the relevant tests and then run them using JUnitCore ?? Thanks !
You can build a org.junit.runner.Request by providing class and method name and pass it to run method of JUnitCoreclass. This will execute given test of the specified class.
Request request = Request.method(TestClass.class, "methodName");
Result result = new JUnitCore().run(request);
You can check the result of test by invoking wasSuccessful() method available in Result class .

How to run also ignored tests in JUnit 4 from command line?

I would like to run some ignored tests from a java program's main method in JUnit 4. They are ignored because they only insert some data for demonstration purpose.
in my main method:
JUnitCore junit = new JUnitCore();
junit.run(MyClass.class);
However this will not run test classes annotated with #Ignored
#Ignore("Only for filling system with demo data")
public class MyClass { ... }
In IntelliJ I can run those by right clicking on the class. How can I run them from the command line / in a main method?
I saw the Runner IgnoredClassRunner but not sure how to use that and if that is the correct Runner/Class.
It turned out this is quite easy achievable with:
JUnitCore junit = new JUnitCore();
junit.run(new BlockJUnit4ClassRunner(MyClass.class));
I will leave this answer open if anybody comes up with something better, which just prevents IgnoredClassRunner to be invoked for classes annotated with #Ignored

Parameterized jUnit tests in Java: Combine 'custom test name' feature (#Parameters(name="namestring")) in jUnit 4.11 with junitparams #FileParameter?

With Parameterized tests in Java, can the 'custom test name' feature exposed in jUnit 4.11 (#Parameters(name="namestring")) be combined with any of the features from Google junitparams?
I have a Java test which cycles through a file containing a set of view names for comparison. Instead of reporting a single test, want each comparison to report out as a separate test instance, each test name customized for the view name supplied as input.
Ideally, would like to use junitparams #FileParameter to load in a file containing the set of names, passing strings into jUnit 'name=' to use as test names and also into the test as input. Both the '#FileParameter' and 'name=' features are relatively simple to implement independently.
Per its doc page, junitparams is 'compliant' with jUnit 4.11, but I haven't figured out a way to combine the two features above. While I can supply both #FileParameter and #Parameters notations to the same test without a syntax or runtime error, the run result seems to ignore the presence of the latter.
Has anyone done this? Is there a better / simpler option? First real question to the Exchange, so please bear with me...
=cjs
JUnit tests that use #Parameters annotation must be run with
#RunWith(Parameterized.class)
However junitparams uses it's own runner
#RunWith(JUnitParamsRunner.class)
A JUnit test can only use a single runner so I don't see how they both can work together unless someone merges the two runners into one.
The easiest solution is to forego junitparams and implement the logic that reads data from the input file and turns it into a parameter list so you can return that from a method annotated with #Parameters.
Another solution is to modify JUnitParamsRunner to behave more like the Parameterized runner does e.g. generate a test with a different name for each parameter read from the input file.
See also:
http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/
Looking at it again, I agree. A little finagling, found junitparams not needed to do what I wanted.
Ugly partial code sample:
#RunWith(Parameterized.class)
public class ParamSampleTest {
#Parameters(name = "{index} myTest : using [arg0 {0}] and [arg1 {1}]")
public static Collection<Object[]> data() throws FileNotFoundException {
return ParamSampleTest.mydataset();
}
private static Collection<Object[]> mydataset() throws FileNotFoundException {
<snip data read, get length>
ArrayList<Object[]> myList = new ArrayList<Object[]>(length);
<snip create String[][], populate, add to myList>
return myList; // return ArrayList of Object[]
}
}

Ant junit batchtest

I have my junit test classes.I am running these class with ant.I am using batchtest attribute with parameter includes="*/ Test *.class" but i have classes with name like * test * that includes no test method and when i run it gives error "no tests found".Is there a option like if no test in the class then skip?
To answer the question you need to supply a better pattern.
Potential solution:
Refactor all legitimate test classes to BEGIN with the prefix Test and than change the ant script to this:
includes="*/Test*.class"
Why do you have classes with the name "Test" in them that aren't tests? I highly recommend following a naming convention that puts Test at the beginning and removing test from your file names that are in fact not tests.

Categories