I am attempting to run a JUnit Test from a Java Class with:
JUnitCore core = new JUnitCore();
core.addListener(new RunListener());
core.run(classToRun);
Problem is my JUnit test requires a database connection that is currently hardcoded in the JUnit test itself.
What I am looking for is a way to run the JUnit test programmatically(above) but pass a database connection to it that I create in my Java Class that runs the test, and not hardcoded within the JUnit class.
Basically something like
JUnitCore core = new JUnitCore();
core.addListener(new RunListener());
core.addParameters(java.sql.Connection);
core.run(classToRun);
Then within the classToRun:
#Test
Public void Test1(Connection dbConnection){
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select total from dual");
rs.next();
String myTotal = rs.getString("TOTAL");
//btw my tests are selenium testcases:)
selenium.isTextPresent(myTotal);
}
I know about The #Parameters, but it doesn't seem applicable here as it is more for running the same test case multiple times with differing values. I want all of my test cases to share a database connection that I pass in through a configuration file to my java client that then runs those test cases (also passed in through the configuration file).
Is this possible?
P.S. I understand this seems like an odd way of doing things.
You can use java system properties to achieve this.
Simply pass what you need with -Dconnectionstring=foobar in the junit command line, or use the java api for system properties to set this programmatically, with System.setProperty(String name, String value), and System.getProperty(String name).
In your tests, you can use the #Before or #BeforeClass to set up common objects based on this property, pending on whether you want to run the setup once for each test (in which case you can use class members) or once for each suite (and then use static members).
You can even factorize this behavior by using an abstract class which all your test cases extends.
Related
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 .
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
I have two test classes each containing a number of tests. I'd like to run both of these together without having to have the #BeforeClass setup method being ran both times. I am calling the classes like this:
public static void main(String[] args) {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { TestClass1.class, TestClass2.class });
testng.addListener(tla);
testng.run();
}
The reason for this is because I have both of them calling in a pop up menu and only want to select the option one time. If this is unclear I will try to further explain.
I have a collection of individual tests across 5 classes. I want each class to be able to run separately, but I also want to make them run collectively should I desire. In the #BeforeClass I have each of them calling another class that will select what URL I want to use (I am testing with TestNG and using Selenium WebDriver).
When this code runs it will execute the #BeforeClass in each class I list, and I would like to, if possible, ignore the #BeforeClass in all the tests if I execute the tests using the code above.
I would recommend passing a transformer in to your TestNG test case that implements, IAnnotationTransformer2. That transformer can allow you to control the behavior of the non #Test Annotations at runtime.
IAnnotationTransformer2
You can use a #BeforeTest in a common class of your 2 test classes.
I understand you want to run the stuff inside #Before only once for your 2 test classes that will be executed at same time together.
If you are using maven + junit 4.x, there is an option for setup things before and after test suit start and complete.
Or you can simply create a #ClassRule at suite level, please see the doc
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
Normally I would have one junit test that shows up in my integration server of choice as one test that passes or fails (in this case I use teamcity). What I need for this specific test is the ability to loop through a directory structure testing that our data files can all be parsed without throwing an exception.
Because we have 30,000+ files that that 1-5 seconds each to parse this test will be run in its own suite. The problem is that I need a way to have one piece of code run as one junit test per file so that if 12 files out of 30,000 files fail I can see which 12 failed not just that one failed, threw a runtimeexception and stopped the test.
I realize that this is not a true "unit" test way of doing things but this simulation is very important to make sure that our content providers are kept in check and do not check in invalid files.
Any suggestions?
I think what you want is parameterized tests. It's available if you're using JUnit4 (or TestNG). Since you mention JUnit, you'll want to look at the #RunWith(Parameterized.class)
and #Parameters annotations' documentation.
I'd write one test that read all the files, either in a loop or some other means, and collected all the failed files in a collection of some kind for reporting.
Maybe a better solution would be a TestNG test with a DataProvider to pass along the list of file paths to read. TestNG will create and run one test for each file path parameter passed in.
A Junit3 answer: Create a TestSuite, that creates the instances of the TestCases that you need, with each TestCase initialized according to your dynamic data. The suite will run as a whole within a single JVM instance, but the individual TestCases are independent of each other (setUp, tearDown get called, the error handling is correct, reporting gives what you asked for, etc).
The actual implementation can be a bit clumsy, because TestCase conflates the Name of the test with the METHOD to be run, but that can be worked around.
We normally just combine the suite with the dynamic testcases in the same class, and use the suite() method to get the TestSuite. Ant's JUnit task is smart enough to notice this, for example.
public class DynamicTest extends TestCase {
String filename ;
public DynamicTest ( String crntFile ) {
super("testMethod");
filename = crntFile ;
}
// This is gross, but necessary if you want to be able to
// distinguish which test failed - otherwise they all share
// the name DynamicTest.testMethod.
public String getName() {
return this.getClass().getName() + " : " + filename ;
}
// Here's the actual test
public void testMethod() {
File f = new File( filename ) ;
assertTrue( f.exists() ) ;
}
// Here's the magic
public static TestSuite suite() {
TestSuite s = new TestSuite() ;
for ( String crntFile : getListOfFiles() ) {
s.addTest( new DynamicTest(crntFile ) ) ;
}
return s ;
}
}
You can, of course, separate the TestSuite from the TestCase if you prefer. The TestCase doesn't hold up well stand alone, though, so you'll need to have some care with your naming conventions if your tests are being auto-detected.