Selectively disable automation cases per environment - java

What I am doing: Using Jenkins to run the same test suites and test cases against various environments - dev / staging / production. I'm using WebDriver with a Java implementation and TestNG.
What I'd like to do: Selectively disable some tests, but not entire test suites, from running depending on the environment. Rather than maintain separate codebases between environments, I'd like to know of a way to accomplish this.
Initial thoughts: I was thinking setting a system property in Jenkins for each job in each environment and each test decorator would have to pull this piece of information out to determine if it should be ran or not. I think it's clunky, I'm not sure how to do it, and I'm not sure if this is the right approach.
Can someone tell me the best way to accomplish this? I'm hoping this isn't the best way.
Thanks,
Joe

Have you looked at TestNG listeners?
You can write a listener which just before the berfore test suite is run BUT after the tests to run have been identifier, to iterate around the list of tests and remove tests you do not want to run.
Because this is programatic you can write any java to achieve what you want.
Also, you could create annotations to identify which tests run in which environment; e.g annotate those tests with something like #RunInEnvironment({"UAT", INT"}); Your listener could then use those annotations to remove tests from the list which are not required.

I think that groups is your answer. With TestNG you can include/exclude groups. You will just need to define which tests are in which groups.
http://testng.org/doc/documentation-main.html#exclusions

#MrTi this solution is rather static and I believe he wants more dynamicity.
If detecting your environment can be done at startup, you may be able to try one of the solution described in that thread. This framework might be useful as well: https://github.com/wolfs/testng-rules
Note: on JUnit you would use Rules https://github.com/lacostej/web-validators/commit/2e1af8e1d9d1bf206849702d4231961563457815 (implementation uses old API)

Related

How to run JUnit5 tests in sequential order?

Is there a way to make tests for specific classes run in sequential order [JUnit5]?. I am using the sure-fire plugin when building the project and my tests on some classes fail, while when I run them in IntelliJ class by class they all pass. I have tried using the Order annotation, but the tests still fail which tells me that this annotation doesn't make tests run in sequential order. I want to make two of my test classes to execute their tests sequentially, while others do it in parallel, but I couldn't find proper solution on how to do that?
P.S. I have added a configuration in the maven sure-fire plugin that runs one JVM process, but this is not the desired behavior that I want to have.
Any help would be appreciated. Thanks in advance!
As described in the JUnit user guide, you can use the #TestMedhodOrder annotation to control the ordering of tests during runtime. For example, to use #Order annotations on the test methods, you would apply #TestMethodOrder(OrderAnnotation.class) at the test class level.
Having said that, you really, really, really should consider that as a last resort. Unless you explicitly and knowingly (fully understanding why) wrote the tests to require a specific ordering, you will just be masking some underlying problem in either your tests or the code they are testing.
Do yourself a favor and do your best to figure out why they fail, instead of putting the band-aid of forced ordering on the problem.

Run code before arquillian deployment

I am writing integration tests for a Java EE Servlet using Arquillian + JUnit. I need to be able to execute code before the server launches.
So is it possible to execute code before #Deployment? I tried #BeforeClass with no luck.
The reason I need to do this, is because trust and keystores for ssl needs to exists before the server starts. I am creating the stores problematically and is saving them to files afterwards.
I know a possible workaround would be to have static trust and keystores, but I prefer to create them programmatically before the test starts for full flexibility when writing tests.
There is not really a need to have your own specialization of Arquillian JUnit runner. This solution would be only for JUnit 4.x in that case which you are using for writing your tests.
Arquillian let you hook through extensions mechanism to its runtime and this way you can have some custom logic executed before server startup to provide your keystores. I believe this is more elegant and portable solution.
Please have a look at sample extensions on Github (especially lifecycle would be a good starting point). If you feel like implementing it this way I'm more than happy to help you. The event you might want to observe on is either BeforeSetup or BeforeStart.
You have two other options for executing code before and after your test:
Rules or ClassRules are executed around and before/after
Using a custom Testrunner (extending the default 'Arquillian' runner)
But as the static deployment method is not invoked by a rule, I assume you have to go for the testrunner.

What are typical uses cases for Test Execution Listeners in Testing Frameworks such as JUnit and TestNG?

JUnit,TestNG, and Spring testing have test execution listeners as an extension mechanism. Test execution listeners seem to be a low level feature of interest to framework developers and tool developers.
What are the main use cases in which Test execution listeners are useful? Can they be useful to application developers?
In Case of testng the listners are the most remarkable thing for me. The testNg listners allows me to simplyfy the test method content and manage each test with server startup , user registration, populating artifacts need for tests . And also clear up the environment for each test cycle.
At the each listener level im performing following operations so i don't have to bother about them in side my tests
IExecutionListener
- onExecutionStart()
Emma instrumentations
Server start
- onExecutionFinish()
Server Sutdown
Emma report generation
ISuiteListener
Set environment properties ex- Key Store Paths
Populate Users.
ITestListener
On Start
Artifact Deployment
On Finish
Artifact Clean up
IReporter
Generate TestNg Report,
Generate sure-fire report,
Export data for Dashboard
For JUnit, the listeners are designed to be a method of reporting, and are used like this internally. So, you can display counts of tests executed, success, failure, error, that sort of thing. This is used externally as well, such as in maven-surefire. See JUnit4RunListener.java as an example.
Another use would be to output in a different format, such as XML. I think the main use cases for the other frameworks are the same.
In JUnit, the listener class is not meant to be used in the manner that Dharshana uses his test listeners in testng, that is as a setup/teardown. The objects used in the Listeners (Description, Failure, Result) are immutable and don't encourage direct access to the test class itself. I'm not sure about TestNG, Cedric would be a better person to ask about that.
Are they useful for an application developers? They may well be, depending upon how your tests are set up. They would only be used in the context of tests, so if they can improve them, then go ahead, use them. One use case would be JUnit test report enrichment with JavaDoc, see my answer. To recap the answer, if the developers add a test for a specific bug, then they can add an annotation to that test linking it back to the bug. There is a custom RunListener, which collects all of the information in the annotations together and produces a report for the final customer.

Better or custom JUnit test filtering

I'd like to implement a better system to filter tests to run under JUnit in Eclipse. I'd like the #Categories, but not have to specify the list of classes in a #SuiteClasses({}) annotation , since I think that reduces the value, increases the amount of manual maintenance we have to do.
Is there some way to hook into the process where Eclipse runs JUnit test, to be able to do custom filtering on all the classes with a #Test in it? E.g. a class like this:
#CustomFilteredTesting
public class TheCustomFilteredTestRun {
public boolean includeThisTestClass(Class<?> klass) {
// e.g. test whether klass is in a package or subsystem
// or a subtype of some interface.
}
}
Any help appreciated, -j
Eclipse uses the default JUnit code to run the tests, so you only need to teach JUnit your new trick and Eclipse will be able to do it.
That out of the way: How can you split tests into suites without #SuiteClasses?
Tough. From my experience, there are several solutions:
Write a test that reads all suites and tries to find all tests and then makes sure that each test is in one suite. This test will let you know when you forgot to add a new test to the suites.
Nice: No JUnit magic involved, will keep you safe if you forget something (like to add a #Category to a new test).
Drawback: Needs quite some ugly File reading/code parsing/reflection mojo.
You can write your own test runner by extending BlockJUnit4ClassRunner. That would allow you to add your own, custom annotations to classify tests and run them.
Add assumptions. org.junit.Assume is a nice little beast to silently fail a test. The test won't run (or it will run until the first assumption fails) but it also won't log an error. It's a bit like a smart #Ignore
Write setup code that determines which tests to run and put assumeThat() in your code.
I actually prefer to use suites because:
The "do I have all tests" test tells when I'm wrong
I have a single place where I can see which test goes where
I can easily write more tests to make sure tests aren't repeated in suites
Consider using ClassPathSuite: http://johanneslink.net/projects/cpsuite.jsp. We use it and define a Suite as follows:
#RunWith(ClasspathSuite.class)
#ExcludeBaseTypeFilter({ NotUnitTestable.class })
public class AllTests {
}
Exclusion is not possible using Annotations so we simply defined a marker interface (NotUnitTestable). We start our tests this way both in Eclipse and in our command line build using the JUnit ANT integration.
Use TestNG. It has test groups, you can see an example on front page. It has better support in parametrized tests. The integration with Spring through spring-test is better.

JUnit vs TestNG [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
At work we are currently still using JUnit 3 to run our tests. We have been considering switching over to JUnit 4 for new tests being written but I have been keeping an eye on TestNG for a while now. What experiences have you all had with either JUnit 4 or TestNG, and which seems to work better for very large numbers of tests? Having flexibility in writing tests is also important to us since our functional tests cover a wide aspect and need to be written in a variety of ways to get results.
Old tests will not be re-written as they do their job just fine. What I would like to see in new tests though is flexibility in the way the test can be written, natural assertions, grouping, and easily distributed test executions.
I've used both, but I have to agree with Justin Standard that you shouldn't really consider rewriting your existing tests to any new format. Regardless of the decision, it is pretty trivial to run both. TestNG strives to be much more configurable than JUnit, but in the end they both work equally well.
TestNG has a neat feature where you can mark tests as a particular group, and then easily run all tests of a specific group, or exclude tests of a particular group. Thus you can mark tests that run slowly as in the "slow" group and then ignore them when you want quick results. A suggestion from their documentation is to mark some subset as "checkin" tests which should be run whenever you check new files in. I never saw such a feature in JUnit, but then again, if you don't have it, you don't REALLY miss it.
For all its claims of high configuration, I did run into a corner case the a couple weeks ago where I couldn't do what I wanted to do... I wish I could remember what it is, but I wanted to bring it up so you know that it's not perfect.
The biggest advantage TestNG has is annotations... which JUnit added in version 4 anyways.
First I would say, don't rewrite all your tests just to suit the latest fad. Junit3 works perfectly well, and the introduction of annotations in 4 doesn't buy you very much (in my opinion). It is much more important that you guys write tests, and it sounds like you do.
Use whatever seems most natural and helps you get your work done.
I can't comment on TestNG b/c I haven't used it. But I would recommend unitils, a great wrapper for JUnit/TestNG/DBUnit/EasyMock, regardless of which route you take. (It supports all the flavors mentioned above)
TestNG's biggest draw cards for me include its support test groups, and more importantly - test group dependencies (marking a test as being dependent of a group causes the tests to simply skip running when the dependent group fails).
TestNG's other big draw cards for me include test parameters, data providers, annotation transformers, and more than anything - the vibrant and responsive user community.
Whilst on the surface one might not think all of TestNGs features above might not be needed, once you start to understand the flexibility bring to your tests, you'll wonder how you coped with JUnit.
(disclaimer - I've not used JUnit 4.x at all, so am unable to really comment on advances or new features there).
About a year ago, we had the same problem. I spent sometime considering which move was better, and eventually we realized that TestNG has no 'killer features'. It's nice, and has some features JUnit 4 doesn't have, but we don't need them.
We didn't want people to feel uncomfortable writing tests while getting to know TestNG because we wanted them to keep writing a lot of tests.
Also, JUnit is pretty much the de-facto standard in the Java world. There's no decent tool that doesn't support it from the box, you can find a lot of help on the web and they added a lot of new features in the past year which shows it's alive.
We decided to stick with JUnit and never looked back.
Cheers to all the above. Some other things I've personally found I like more in TestNG are:
The #BeforeClass for TestNG takes place after class creation, so you aren't constrained by only being able to call static methods of your class in it.
Parallel and parameterized tests, maybe I just don't have enough of a life... but I just get a kick writing one set of Selenium tests, accepting a driver name as a parameter. Then defining 3 parallel test groups, 1 each for the IE, FF and Chrome drivers, and watching the race! I originally did 4, but way too many of the pages I've worked on break the HtmlUnit driver for one reason or another.
Yeah, probably need to find that life. ;)
I wanted to share the one I encountered today. I found built-in Parameterized runner is quite crude in Junit4 as compare to TestNG (I know each framework has its strengths but still). The Junit4 annotation #parameters is restricted to one set of parameters. I encountered this problem while testing the valid and invalid behavior for functionality in same test class. So the first public, static annotated method that it finds will be used, but it may find them in any order. This causes us to write different classes unnecessarily. However TestNG provides clean way to provide different kind of data providers for each and every method. So we can test the same unit of code with valid and invalid way in same test class putting the valid/invalid data separately. I will go with TestNG.
Also one more advantage of TestNG is supporting of parallel testing. In our era of multicores it's important, i think.
I also used both frameworks. But i using hamcrest for assertations. Hamcrest allows you easily write your own assert method. So instead of
assertEquals(operation.getStatus(), Operation.Status.Active);
You can write
assertThat(operation, isActive());
That gives you opportunity to use higher level of abstraction in your tests. And this makes your tests more robust.
JUnit 4 Vs TestNG – Comparison by mkyong.com ( updated on 2013).
Conclusion: I suggest to use TestNG as core unit test framework for Java project, because TestNG is more advance in parameterize testing, dependency testing and suite testing (Grouping concept).
TestNG is meant for functional, high-level testing and complex integration test. Its flexibility is especially useful with large test suites.
In addition, TestNG also cover the entire core JUnit4 functionality. It’s just no reason for me to use JUnit anymore.
In simple terms, TestNG = JUnit + lot more. So, Why debate ? go and
grab TestNG :-)
You can find more detailed comparison here.
Why we use TestNG instead of JUnit?
The declaration of #BeforeClass and #AfterClass method has to be static in JUnit whereas, there is more flexibility in TestNG in the method declaration, it does not have these constraints.
In TestNG, we can parametrize tests using 2 ways. #Parameter or #DataProvider annotation.
i) #Parameter for simple cases, where key value mapping is required.(data is provided through xml file)
ii) #DataProvider for complex cases. Using 2 dimensional array, It can provide data.
In TestNG, since #DataProvider method need not be static, we can use multiple data provider methods in the same test class.
Dependency Testing: In TestNG, if the initial test fails, then all subsequent dependent tests will be skipped, not marked as failed. But JUnit marked it failed.
Grouping: Single tests can belong to multiple groups and then run in different contexts (like slow or fast tests). A similar feature exists in JUnit Categories but lacks the #BeforeGroups / #AfterGroups TestNG annotations that allow initializing the test / tearing it down.
Parallelism: If you’d like to run the same test in parallel on multiple threads, TestNG has you covered with a simple to use annotation while JUnit doesn’t offer a simple way to do so out of the box.
TestNG #DataProvider can also support XML for feeding in data, CSVs, or even plain text files.
TestNG allows you to declare dependencies between tests, and skip them if the dependency test didn’t pass.
#Test(dependsOnMethods = { "dependOnSomething" })
This functionality doesn’t exist in JUnit
Reporting:
TestNG reports are generated by default to a test-output folder that includes HTML reports with all of the test data, passed/failed/skipped, how long did they run, which input was used and the complete test logs. In addition, it also exports everything to an XML file which can be used to construct your own report template.
On the JUnit front, all of this data is also available via XML, but there’s no out of the box report and you need to rely on plugins.
Resource Link:
A Quick JUnit vs TestNG Comparison
JUnit vs. TestNG: Which Testing Framework Should You Choose?
A good difference is given in this tutorial side by side: TestNG Vs JUnit: What's the Difference?
A couple of additions to Mike Stone's reply:
1) The most frequent thing I use TestNG's groups for is when I want to run a single test method in a test suite. I simply add this test to the group "phil" and then run this group. When I was using JUnit 3, I would comment out the entries for all methods but the one I wanted to run in the "suite" method, but then would commonly forget to uncomment them before checkin. With the groups, I no longer have this problem.
2) Depending on the complexity of the tests, migrating tests from JUnit3 to TestNG can be done somewhat automatically with sed and creating a base class to replace TestCase that static imports all of the TestNG assert methods.
I have info on my migration from JUnit to TestNG here and here.
My opinion about what makes TestNG truly far more powerful:
1. JUnit still requires the before/after class methods to be static, which limits
what you can do prior to the running of tests, TestNG never has this issue.
2. TestNG #Configuration methods can all take an optional argument to their
annotated methods in the form of a ITestResult, XmlTest, Method, or
ITestContext. This allows you to pass things around that JUnit wouldn't
provide you. JUnit only does this in listeners and it is limited in use.
3. TestNG comes with some pre-made report generation classes that you can copy
and edit and make into your own beautiful test output with very little
effort. Just copy the report class into your project and add a listener
to run it. Also, ReportNG is available.
4. TestNG has a handful of nice listeners that you can hook onto so you can do
additional AOP style magic at certain phases during testing.
Your question seems two folded to me. On one had you would like to compare two test frameworks, on the other hand you would like to implement tests easily, have natural assertions, etc...
Ok, firstly JUnit has been playing catchup with TestNG in terms of functionality, they have bridged the gap some what with v4, but not well enough in my opinion. Things like annotations and dataproviders are still much better in TestNG. Also they are more flexible in terms of test execution, since TestNG has test dependency, grouping and ordering.
JUnit still requires certain before/after methods to be static, which limits what you can do prior to the running of tests, TestNG never has this issue.
TBH, mostly the differences between the two frameworks don't mean much, unless your focusing on integration/automation testing. JUnit from my experience is built from the ground up for unit testing and is now being pushed towards higher levels of testing, which IMO makes it the wrong tool for the job. TestNG does well at unit testing and due to its robust dataproviding and great test execution abilities, works even better at integration/automation test level.
Now for what I believe is a separate issue, how to write well structured, readable and maintainable tests. Most of this I am sure you know, but things like Factory Pattern, Command Pattern and PageObjects (if your testing websites) are vital, it is very important to have a layer of abstraction between what your testing (SUT) and what the actual test is (assertions of business logic). In order to have much nicer assertions, you can use Hamcrest. Make use of javas inheritance/interfaces to reduce repetition and enforce commonality.
Almost forgot, also use the Test Data Builder Pattern, this coupled with TestNG's dataprovider annotation is very useful.

Categories