1
votes

It seems like with JUnit class variable has different scope rules which I guess needs to be managed with test fixtures. so here is what I want

I have test suite, test class and I have two methods (test1,test2) in this test class, I have class variable temp in test class, and I assign some value to this variable in test1 and want to access this value in test2

@RunWith(Suite.class)
@Suite.SuiteClasses(
        {                                               
            LoginTest.class

        })

  public class SanitySuite {

     @BeforeClass
     public static void setUp(){
         BuildTest.seleniumSetUp();
        }

        @AfterClass
        public static void tearDown() throws Exception{
            BuildTest.seleniumTearDown();
        }
}


public class LoginTest{
 String temp=null; 

  @Test
   public void test1(){
    temp = "abc"
   }
   @Test
   public void test2(){
    system.out.print(temp)//prints null
   }
}

any pointers on how to retrieve the value of temp in test2 with test fixtures?

3

3 Answers

3
votes

The way variables work in jUnit is that they get initialized before each test. So if you assigned temp = "abc" in test1, it will be reinitialized when test2 run. If you want to some kind of initialization before each test, use the setup method.

For unit tests your aim should be to test the smallest isolated piece of code,usually, method one by one. So sharing variables between test cases does not seem to be a good idea. But if you really need to do something like that, then one approach can be to club the two methods in one method and use the variable set by the first in the second.

1
votes

By and large, your use case is not supported by JUnit and for a good reason: you want the test to be independent of each other. Thus, every test method runs on its on object. In other words, when you run your test case, behind the scenes, JUnit is doing the following

new LoginTest().test1();
new LoginTest().test2();

If you want both test1() and test2() to access the same field (and have the same value) you can initialize it in the constructor:

public class LoginTest() {
   String temp;
   public LoginTest() {  temp = "abc"; }

   @Test public void test1() { ... }
   @Test public void test2() { ... }
}

You can also use a @Before method that will be invoked before every test but that is equivalent to initializing a field in the ctor so it is not that useful.

0
votes

Use ReflectionUtil class to assign values:

ReflectionTestUtils.setField(nameofClass, "nameOfMemberVariable","Value");