0

I am very new to java and junit. I have sometest cases under test/pagetests like addTest.java , deleteTest.java. I have included these tests under junit test suite by using the code below

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
addTest.class,
deleteTest.class
})
public class JunitTestSuite {  
}  

All these test cases uses inputs from db. for this i have wrote a method called getValues in TestDBMethods.java which is in the path test/testdb which returns all the values which i need in my test cases.

the problem i am facing is i dont want to call the class TestDBMethods.java in each and every test case as this is very expensive. so i prefer to include a singleton class which calls TestDBMethods.java only once and returns an instance that should be made use by all the other test cases. Could anyone please help me in writing code for the singleton class which calls the class TestDBMethods.java and return an instance.

user2458408
  • 79
  • 1
  • 3
  • 6
  • Looks like you need to use setup method: http://stackoverflow.com/questions/512184/best-practice-initialize-junit-class-fields-in-setup-or-at-declaration – Salil Nov 23 '13 at 02:34
  • However, your unit tests should not query database and get test values because unit tests are supposed to run quickly. Can't you embed these test values in the test classes themselves? – Salil Nov 23 '13 at 02:37

1 Answers1

0

From your description ,Since calling TestDBMethods is expensive,So you can just implement TestDBMethods as a singleton class,instead of the class who calls TestDBMethods.

As I know,we have many ways to implement a singleton ..Below is just a very simple example:

 public class TestDBMethods{  
      private static TestDBMethods instance;  
      private TestDBMethods(){}   
     public static TestDBMethods getInstance() {  
      if (instance == null) {  
          instance = new TestDBMethods();  
     }  
      return instance;  
      }

  public Object getValues(){
      return null;
  }  
 }  

In this way ,you can just use TestDBMethods.getInstance.getValue() to call the function getValue(),and there exists only one instance in memory.

wuchang
  • 3,003
  • 8
  • 42
  • 66