user1121210
user1121210

Reputation: 83

How to do junit testing for multiple functions together

I am writing Junit test cases for one java application. If I run the test functions individually its running fine. When I try to run them together its not running properly

Here is JUnit code

 public class CultureMachineTestCases{

     CultureMachineAssignment testObj=new CultureMachineAssignment ();
     HashSet<String> result =new HashSet<String>();
     String answer,answer1;
     int flagVal;
     @Before
     public void init() throws IOException{
         testObj.insertDataIntoSet();
         testObj.addKeywords("video1");
      }

     @Test
     public void testVideo() throws IOException {
        result=testObj.search("abcd");
        answer=result.toString();
        answer1=answer.replaceAll("[^a-z0-9]","");

          assertEquals("video1", answer1);

     }
     @Before
     public void initMethod() throws IOException{
         testObj.insertDataIntoSet();
         testObj.addKeywords("video2");
      }    
      @Test
      public void testLenth() throws IOException{
         flagVal=testObj.flag;

        assertEquals(1, flagVal);
     }
 }

Here flag is set to one in CultureMachineAssignment file. Can any one please tell me what I need to do so I can run all the functions inside test file together

Upvotes: 1

Views: 268

Answers (1)

rgrebski
rgrebski

Reputation: 2584

@Before annotated method (init()) is called before every test method. You should only have one method annotated with @Before not to get confused.

The code you have implemented in init() should be moved to testVideo() and code from initMethod() should be moved to testLength().

And your init method should look like this to be sure that test class state is the same for all tests:

@Before
public void init(){
  answer = null;
  answer1 = null;
  flagVal = -1;
  result = new HashSet<String>();
}

Upvotes: 3

Related Questions