Im using testng 6.11 and writing tests in the following test class:
public class MyTest{
public int i;
public void init(){
//initialize i
}
#Test
public void test1(){
//test some
}
#Test
public void test2(){
//Here I need fresh value of i as it would be
//right after invocation of init()
//...
//test something else
}
}
Is it possible to make testng run init() method before invocation of each test in a test class?
Annotate init() with #BeforeMethod annotation. See http://testng.org/doc/documentation-main.html#annotations
Sure, your can use the annotation for that
#BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
You can use #BeforeMethod annotatation to execute any method before every test.
Example
Related
I would like know, how can I make a JUnit ignore #Before only in oone method Test.
I found how to ignore in a Class, but I need only in one Test.
You may use #Rule for that. Here is an example:
public class ExampleUnitTest {
#Rule
public TestName testName = new TestName();
#Before
public void init() {
if (testName.getMethodName().equals("someTest")) {
// your logic for the `someTest` method
} else {
// logic for the rest of the tests
}
}
#Test
public void someTest() {
//
}
#Test
public void anotherTest() {
//
}
#Test
public void yetAnotherTest() {
//
}
}
However, how #mslowiak pointed already, this is not a good idea. The JUnit core concept is test isolation. So, if you need different init steps for the different tests you might be doing something wrong.
The reason for #Before annotation is to have consistent behavior in every test.
In your case extracting before logic to a method and call it with each required test would be a better idea.
My #Before and #After methods are not picking up by Junit
public class TestSetup {
#Before
public void browserSetUp() {
// code for before a test
}
#After
public void tearDown() {
// code after a test
}
}
In Another class file I have defined
public class Steps{
#Step
public void step1() {
//Code for step 1
}
#Step
public void step2() {
// Code for Step 2
}
}
Finally I am calling those steps for my Test
public class Tests {
Steps step = new Steps();
#Test
public void TC_0001 {
step.step1();
step.step2();
}
}
#Test method are getting executed but the #Before and #After methods are not executing before #Test method.Do I have to include the TestSetup class to somewhere ? Any help will be appreciated.
**Thought 1: As I am using Maven to build, my #Before #After methods resides in a class (TestSetup.java - Name is not ending with *Test.java and may be thats why Maven is not picking it up for execution?
#Before and #After are used in the same class that your test is running. You should put this methods on your test class:
public class Tests {
Steps step = new Steps();
#Test
public void TC_0001 {
step.step1();
step.step2();
}
#Before
public void browserSetUp() {
// code for before a test
}
#After
public void tearDown() {
// code after a test
}
}
#Before and #After are only executed before a single test, if they are defined in the same class as the #Test. In your case, the TestSetup class contains no tests. So either you let Test inherit from TestSetup or you create a rule that is executed "around" your test.
I have few JUnit Tests and I want to decide which one to use at runtime. I checked previous answers at SO and I ended up creating Test Suite dynamically.
This class is where my application starts. I have CustomTestSuite class and Main class adds Tests to my custom suite.
public class Main {
public static junit.framework.TestSuite suite()
{
CustomTestSuite suite = new CustomTestSuite();
suite.addTest(new JUnit4TestAdapter(BTest.class));
suite.addTest(new JUnit4TestAdapter(ATest.class));
return suite;
}
}
CustomTestSuite.java
public class CustomTestSuite extends TestSuite {
#BeforeClass
public static void setUp() throws Exception {
System.out.println("Before class test");
}
#After
public void tearDown() throws Exception {
System.out.println("After class test");
}
}
My ATest and BTest are simple Test classes, I will just show ATest as sample:
public class ATest{
#Test
public void testMethod() {
System.out.println("testMethod");
}
}
When I start running my project from Main class, it is expected to run the method with #BeforeClass first, do testing, and then run the method with #AfterClass annotation.
Tests are working fine but it skips setUp method and tearDown method. I tried #Before and #BeforeClass annotations both.
I am confused with suite structure. Any help would be appreciated.
Thanks
#Before and #BeforeClass are supposed to be used in Test class not in TestSuite. If need to have common setUp and tearDown for more than one Test class, then put those both methods in a super class and extend that super by ATest and BTest test classes. And also the Suite can be built and run simply with #RunWith and #SuiteClasses annotations and the CustomTestSuite class is not needed.
So the changes are as below.
The CustomTestSuite becomes TestSuper
public class TestSuper {
#BeforeClass
public static void setUp() throws Exception {
System.out.println("Before class test");
}
#After
public void tearDown() throws Exception {
System.out.println("After class test");
}
}
Now the ATest extends TestSuper
public class ATest extends TestSuper {
#Test
public void testMethod() {
System.out.println("testMethod");
}
}
Similarly BTest also should extend TestSuper.
Simply add #RunWith and #SuiteClasses annotations to Main class as below and run Main.
#RunWith(Suite.class)
#SuiteClasses({ATest.class, BTest.class})
public class Main {
}
Have a go with these changes.
I set up a class with a couple of tests and rather than using #Before I would like to have a setup method that executes only once before all tests. Is that possible with Junit 4.8?
Although I agree with #assylias that using #BeforeClass is a classic solution it is not always convenient. The method annotated with #BeforeClass must be static. It is very inconvenient for some tests that need instance of test case. For example Spring based tests that use #Autowired to work with services defined in spring context.
In this case I personally use regular setUp() method annotated with #Before annotation and manage my custom static(!) boolean flag:
private static boolean setUpIsDone = false;
.....
#Before
public void setUp() {
if (setUpIsDone) {
return;
}
// do the setup
setUpIsDone = true;
}
You can use the BeforeClass annotation:
#BeforeClass
public static void setUpClass() {
//executed only once, before the first test
}
JUnit 5 now has a #BeforeAll annotation:
Denotes that the annotated method should be executed before all #Test
methods in the current class or class hierarchy; analogous to JUnit
4’s #BeforeClass. Such methods must be static.
The lifecycle annotations of JUnit 5 seem to have finally gotten it right! You can guess which annotations available without even looking (e.g. #BeforeEach #AfterAll)
When setUp() is in a superclass of the test class (e.g. AbstractTestBase below), the accepted answer can be modified as follows:
public abstract class AbstractTestBase {
private static Class<? extends AbstractTestBase> testClass;
.....
public void setUp() {
if (this.getClass().equals(testClass)) {
return;
}
// do the setup - once per concrete test class
.....
testClass = this.getClass();
}
}
This should work for a single non-static setUp() method but I'm unable to produce an equivalent for tearDown() without straying into a world of complex reflection... Bounty points to anyone who can!
JUnit 5 #BeforeAll can be non static provided the lifecycle of the test class is per class, i.e., annotate the test class with a #TestInstance(Lifecycle.PER_CLASS) and you are good to go
Edit:
I just found out while debugging that the class is instantiated before every test too.
I guess the #BeforeClass annotation is the best here.
You can set up on the constructor too, the test class is a class after all.
I'm not sure if it's a bad practice because almost all other methods are annotated, but it works. You could create a constructor like that:
public UT () {
// initialize once here
}
#Test
// Some test here...
The ctor will be called before the tests because they are not static.
Use Spring's #PostConstruct method to do all initialization work and this method runs before any of the #Test is executed
Try this solution:
https://stackoverflow.com/a/46274919/907576 :
with #BeforeAllMethods/#AfterAllMethods annotation you could execute any method in Test class in an instance context, where all injected values are available.
My dirty solution is:
public class TestCaseExtended extends TestCase {
private boolean isInitialized = false;
private int serId;
#Override
public void setUp() throws Exception {
super.setUp();
if(!isInitialized) {
loadSaveNewSerId();
emptyTestResultsDirectory();
isInitialized = true;
}
}
...
}
I use it as a base base to all my testCases.
If you don't want to force a declaration of a variable that is set and checked on each subtest, then adding this to a SuperTest could do:
public abstract class SuperTest {
private static final ConcurrentHashMap<Class, Boolean> INITIALIZED = new ConcurrentHashMap<>();
protected final boolean initialized() {
final boolean[] absent = {false};
INITIALIZED.computeIfAbsent(this.getClass(), (klass)-> {
return absent[0] = true;
});
return !absent[0];
}
}
public class SubTest extends SuperTest {
#Before
public void before() {
if ( super.initialized() ) return;
... magic ...
}
}
I solved this problem like this:
Add to your Base abstract class (I mean abstract class where you initialize your driver in setUpDriver() method) this part of code:
private static boolean started = false;
static{
if (!started) {
started = true;
try {
setUpDriver(); //method where you initialize your driver
} catch (MalformedURLException e) {
}
}
}
And now, if your test classes will extends from Base abstract class -> setUpDriver() method will be executed before first #Test only ONE time per run.
Here is one alternative suggestion:
What I do to get this working is
Create a method named _warmup or just _
Annotate the test class with #FixMethodOrder(MethodSorters.NAME_ASCENDING)
This is applicable only if you run all tests in the class
It has a downside of having additional test included, which will also run one additional #Before and #After
It is usually advised for your test methods to be order independent, this breaks that rule, but why someone would like tests ordered randomly in the reports I have no clue so NAME_ASCENDING is what I always use
But the upsides to this is simple setup with minimal code and without the need to extend classes/runners etc...
Test run lengths are more accurate since all setup time is reported on method _warmup
After experimenting for some time this is my solution. I needed this for spring boot test. I tried using #PostConstruct, unfortunately it is executed for every test.
public class TestClass {
private static TestClass testClass = null;
#Before
public void setUp() {
if (testClass == null) {
// set up once
...
testClass = this;
}
}
#AfterClass
public static void cleanUpAfterAll() {
testClass.cleanUpAfterAllTests();
}
private void cleanUpAfterAllTests() {
// final cleanup after all tests
...
}
#Test
public void test1() {
// test 1
...
}
#Test
public void test2() {
// test 2
...
}
}
The problem with #BeforeClass is that it fires before the constructor.
So if you rely on an #Autowired constructor to provide data, it simply will not work: wrong execution order.
Similarly #PostConstruct fires after the constructor has been called. And the constructor fires with every #Test, therefore your setup function will fire with every test, if you use this.
This has the exact same effect as calling a function from the constructor.
The only solution, I found that works, is to use a flag to indicate if the setUp() method has already been executed. While its not ideal, it will drastically reduce the amount of processing before each test.
private static boolean initialized = false;
#Autowired
public CacheTest( MyBean myBean ){
this.myBean = myBean;
}
#PostConstruct
public static void setUp(){
if( initialized ) { return };
initialized = true;
//do suff with myBean
}
I have an Integration Test Suite. I have a IntegrationTestBase class for all my tests to extend. This base class has a #Before (public void setUp()) and #After (public void tearDown()) method to establish API and DB connections. What I've been doing is just overriding those two methods in each testcase and calling super.setUp() and super.tearDown(). However this can cause problems if someone forgets to call the super or puts them at the wrong place and an exception is thrown and they forget to call super in the finally or something.
What I want to do is make the setUp and tearDown methods on the base class final and then just add our own annotated #Before and #After methods. Doing some initial tests it appears to always call in this order:
Base #Before
Test #Before
Test
Test #After
Base #After
but I'm just a little concerned that the order isn't guaranteed and that it could cause problems. I looked around and haven't seen anything on the subject. Does anyone know if I can do that and not have any problems?
Code:
public class IntegrationTestBase {
#Before
public final void setUp() { *always called 1st?* }
#After
public final void tearDown() { *always called last?* }
}
public class MyTest extends IntegrationTestBase {
#Before
public final void before() { *always called 2nd?* }
#Test
public void test() { *always called 3rd?* }
#After
public final void after() { *always called 4th?* }
}
Yes, this behaviour is guaranteed:
#Before:
The #Before methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.
#After:
The #After methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.
One potential gotcha that has bitten me before:
I like to have at most one #Before method in each test class, because order of running the #Before methods defined within a class is not guaranteed. Typically, I will call such a method setUpTest().
But, although #Before is documented as The #Before methods of superclasses will be run before those of the current class. No other ordering is defined., this only applies if each method marked with #Before has a unique name in the class hierarchy.
For example, I had the following:
public class AbstractFooTest {
#Before
public void setUpTest() {
...
}
}
public void FooTest extends AbstractFooTest {
#Before
public void setUpTest() {
...
}
}
I expected AbstractFooTest.setUpTest() to run before FooTest.setUpTest(), but only FooTest.setupTest() was executed. AbstractFooTest.setUpTest() was not called at all.
The code must be modified as follows to work:
public void FooTest extends AbstractFooTest {
#Before
public void setUpTest() {
super.setUpTest();
...
}
}
I think based on the documentation of the #Before and #After the right conclusion is to give the methods unique names. I use the following pattern in my tests:
public abstract class AbstractBaseTest {
#Before
public final void baseSetUp() { // or any other meaningful name
System.out.println("AbstractBaseTest.setUp");
}
#After
public final void baseTearDown() { // or any other meaningful name
System.out.println("AbstractBaseTest.tearDown");
}
}
and
public class Test extends AbstractBaseTest {
#Before
public void setUp() {
System.out.println("Test.setUp");
}
#After
public void tearDown() {
System.out.println("Test.tearDown");
}
#Test
public void test1() throws Exception {
System.out.println("test1");
}
#Test
public void test2() throws Exception {
System.out.println("test2");
}
}
give as a result
AbstractBaseTest.setUp
Test.setUp
test1
Test.tearDown
AbstractBaseTest.tearDown
AbstractBaseTest.setUp
Test.setUp
test2
Test.tearDown
AbstractBaseTest.tearDown
Advantage of this approach: Users of the AbstractBaseTest class cannot override the setUp/tearDown methods by accident. If they want to, they need to know the exact name and can do it.
(Minor) disadvantage of this approach: Users cannot see that there are things happening before or after their setUp/tearDown. They need to know that these things are provided by the abstract class. But I assume that's the reason why they use the abstract class
If you turn things around, you can declare your base class abstract, and have descendants declare setUp and tearDown methods (without annotations) that are called in the base class' annotated setUp and tearDown methods.
You can use #BeforeClass annotation to assure that setup() is always called first. Similarly, you can use #AfterClass annotation to assure that tearDown() is always called last.
This is usually not recommended, but it is supported.
It's not exactly what you want - but it'll essentially keep your DB connection open the entire time your tests are running, and then close it once and for all at the end.
This isn't an answer to the tagline question, but it is an answer to the problems mentioned in the body of the question. Instead of using #Before or #After, look into using #org.junit.Rule because it gives you more flexibility. ExternalResource (as of 4.7) is the rule you will be most interested in if you are managing connections. Also, If you want guaranteed execution order of your rules use a RuleChain (as of 4.10). I believe all of these were available when this question was asked. Code example below is copied from ExternalResource's javadocs.
public static class UsesExternalResource {
Server myServer= new Server();
#Rule
public ExternalResource resource= new ExternalResource() {
#Override
protected void before() throws Throwable {
myServer.connect();
};
#Override
protected void after() {
myServer.disconnect();
};
};
#Test
public void testFoo() {
new Client().run(myServer);
}
}