views:

58

answers:

4

I'm using JUnit. I want to invoke assertEquals() many times in a test method to test many diferent test cases but I don't want to have many test method. So I use setUp() and tearDown(). But when the first assertEquals() fail.The second assertEquals()doesn't work and setUp() method just have been invoked one time.

Here is my code

public class ComputeServiceTest extends TestCase {

private ComputeServices instance = new ComputeServices();


public ComputeServiceTest(String name)
{
 super(name);  
}

protected void setUp()
{
 System.out.println("aaaaaaaaaaaaaaaaaaaaa");
 instance  = new ComputeServices();
}

protected void tearDown() {

}

//test add method
public void testAdd1()
{    
 //instance = new ComputeServices();
 //First test case 
    int x1 = 7;
    int y1 = 5;

    int expResult1 = 13;
    int result1 = instance.add(x1, y1);
    assertEquals("First test case fail",expResult1, result1);   

    // Second test case
    System.out.println("AAAAAAAAAAAAAAAAAAAAAaaaaaaaaaa");
    int x2 = 9;
    int y2 = 6;

    int expResult2 = 16;

    int result2 = instance.add(x2, y2);
    assertEquals("Second test case fail",expResult2, result2);
}

}

Pls help me to fix thi bug.

+3  A: 

Try using parametrized tests.

cetnar
A: 

You should make them work or if that's not you want right now, write them into many test methods.

Regards

Mike [;-)

DerMike
A: 

If you really wants to do have one test method only, you could have a single assertion at the end of your unique test method:

assertEquals("my big assertion", 
             true, 
             ((expResult1==result1) && (expResult2, result2));

But I won't recommend that: how would you know which test failed then ? You won't have any detail.

Why don't you want to avoid having several test methods in your TestCase ? There could be another way to achieve what you want.

philippe
+3  A: 

I don't think you are using the tool (JUnit) correctly.

A unit test can either fail or success, there is no such a thing as a half-succeeded or half-failed test.

A single setup has to be enough for every test, if you need more than one setup call then you are putting many tests in one.

I don't think there is any drawback on splitting your test into many smaller tests. Setup and teardown shouldn't be very heavy, tests should alway run in the order of ms and the higher the granularity of the test the better, so you know exactly what functionality has stopped working.

Iker Jimenez