Java pass arguments dynamically to a junit test - java

I'm doing a special junit test, that the params are introduced in the front-end of the application by the user and received in back-end of the application. And i want to generate junit test that use that information as parameters.
I saw some guide (like mykong guide and tutorial points) but most of them use static parametrized and i want some dynamic thing. I already tried to use junit annotations, do a set or pass the params to the junit class, use mockito methods but nothings work as dynamic process
Can someone point me to the right direction?
Right now i have something like that
public void run (Object foo) //Class that contains the information introduced by the user
JUnitCore junit1 = new JUnitCore();
Result result4 = JUnitCore.runClasses(GeneratedTest.getClass()); //Junit class
//I tried: do a setFoo on the GeneratedTest ; pass the foo on the constructor;
for (Failure failure : result4.getFailures()) {
System.out.println(failure.toString());
}

Probably not the nicest solution, but maybe an acceptable workaround:
generate your unit test so that it fetches parameters from System properties
run the generated JUnit test in its own JVM, and pass the parameters/properties on the command line

Related

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 avoid external call in JUnit Groovy

Finally I am able to get Groovy class in my Java file and able to perform JUnit on my groovy classes. Now my problem is I want to test my method which triggers RPC calls.but I want to avoid that call in unit test. How should I do that? Below is my sample code for logout how I am proceeding
#Test
public void logoutTest() {
GroovyObject loginOject =new Login();
GroovyObject logoutObject =new Logout();
XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) loginOject.invokeMethod(
"getServerProxy",
"https://urlproxy"
);
String sessionId = (String) loginOject.invokeMethod(
"getSession",
new Object[]{"username","password",serverProxy}
);
logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy});
}
You can do so by using mocks. I assume you are testing logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy}); method which calls a method on your XMLRPCServerProxy serverProxy. If you a have an option to introduce a dependency on mocking framework such as Mockito you can then create a mock instead of
XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) oginOject.invokeMethod("getServerProxy", "https://urlproxy");
You can mock it
XMLRPCServerProxy serverProxy = mock(XMLRPCServerProxy.class);
when(serverProxy.sendRequest("payload")).thenReturn("result");
If you cannot use a mock library you can extend XMLRPCServerProxy in the test and override a method that does rpc call to do whatever you want (this is effectively what Mockito would do for you)
XMLRPCServerProxy proxyServer = new XMLRPCServerProxy() {
public String request(String payload) {
// your mock code
return "result";
}
};
I'd recommend using Spock for unit-testing Groovy (and Java) code. Latest when it comes to mocking, no Java tool / framework I know is capable of properly mocking Groovy stuff as the language is simply too dynamic to be handled by tools written to hook into Java code.
Spock is written in Groovy and with Groovy in mind when it comes to mocking and stubbing. Spock might look a bit alien if you first look at it, but if you get used to the syntax it is quite amazing what you can do and how easy you can write tests with variying input data and so on.
Spock also is based on JUnit, so every tool that is able to execute and evaluate JUnit tests is also able to cope with Spock tests.

How to change the #Test method dynamically in TestNG

This is more of a question on test automation framework design. Very hard indeed to summarize whole question in one line :)
I am creating a test automation framework using Selenium. Mostly I am accessing the data (methods name) from an excel file.
In my main Runner class I am getting a list of test cases. Each test case has a set of methods (can be same or different) which I have defined in a java class and executing each method using java reflection api. Everything is fine till this point.
Now I want to incorporate TestNG and reporting/logging in my automation suite. Problem is I cant use #Test for each method as TestNG considers #Test = 1 Test Case - but my 1 Test case might have more than 1 methods. My methods are more like a test steps for a test case, reason is I dont want repeat the code. I want to create a #Test dynamically calling different sets of methods and executing them in Java Or defining each teststeps for a #Test. I was going through the TestNG documentation, but could not able to locate any feature to handle this situation.
Any help is really appreciated and if you have any other thoughts to handle this situaton I am here to listen.
Did you try the following?
#Test(priority = 1)
public void step1() {
//code
}
#Test(priority = 2)
public void step2() {
//code
}
You need to use "priority" for each method, otherwise it won't work.

A Parameterized Parameterized test or Parameterized Suite with a before and after

I have an #Parameterized JUnit test which all works. Now I'm trying to create a new test that runs that same #Parameterized test once for 20 database configurations.
Been having a look online and there are various people who have asked for this but there doesn't seem to be a satisfactory solution. I had a look at Suite but it can't run Parameterized test and it doesn't have any annotations that can be run in between the suite tests to prepare for the next suite test.
Standard Parameterized class:
#RunWith(Parameterized.class)
public class MyParameterizedTest {
// works as normal
}
Here is some pseudo code of what I am looking for:
#RunWith(RunParameterizedLots.class)
#ParameterizedClassToTest(MyParameterizedTest.class)
public class RunParameterizedLotsOfTimes<T> {
#ListOfTestStuff
public List<T> getList() {
return list of T;
}
#BeforeRunningMyParameterizedTest
public void beforePtest(T i) {
setupDatabaseConfig(i);
}
#AfterRunningMyParameterizedTest
public void afterPtest() {
teardownDatabaseConfig(i);
}
}
None of this is written I have spent 2 days reading JUnit documentation and don't seem to be any closer. Release notes for 4.12 talk about #UseParametersRunnerFactory which looks like it might help, there is also some stuff with the new BlockJUnit4ClassRunnerWithParameters but there doesn't seem to be any example of how to use it.
I could create a "#RunWith(Parameterized.class)" class that feeds 1,2,3,4 into itself but then how to I link the sub-parameterized tests into the JUnit subsystem so it looks nice and provides sensible display.
I hope you can see from my waffle question what I am trying to do I just don't know where to start or if someone else has done this work already?
Out of the box it's not possible to parameterize a JUnit test suite, because both are Runners and you may only have one #RunWith() annotation at your test.
For that cause I wrote a new Runner that combines the functionality of both to a ParameterizedSuite: https://github.com/PeterWippermann/parameterized-suite
Good news is, it also enables you to use #Before and #After!
However, I'm not sure if your problem isn't somewhat different: Don't you have two parameters? You say, you already have a parameterized test and now you wan't to run that test against a list of database configurations. So that would be your second parameter. You would like to test all combinations of those two parameters, wouldn't you?

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[]
}
}

Categories