天天看點

Unit Test 學習筆記

public class MyTest extends TestCase {
private int count = 0;
public void test1() {
count++;
assertEquals(1, count);
}
public void test2() {
count++;
assertEquals(1, count);
}
}
           

 Take a quick look at this test case and imagine running it with JUnit.

What do you think will happen? Pass or fail?

The answer: It passes.

I remember shaking my head in disbelief when I saw this result. I truly

couldn’t believe my eyes, and I was certain that I had been working too

much and that I wasn’t thinking straight. But debugging into the JUnit code

confirmed this observation: JUnit reinstantiates the test class before each

test method, thereby explaining why the count field is reset to zero each

time.

Test methods with JUnit have the following constraints.

■ Their names need to start with test.

■ They can’t return any values.

■ They can’t have any parameters.

This last restriction is something that has often bothered us. Why can’t

we pass parameters to our test methods? After all, passing parameters to

methods and functions is an idea that has been present in programming languages

for decades, and we can’t think of a programmer who wouldn’t be

familiar with the idea.

Passing parameters to test methods seems to be very natural and, sometimes,

extremely practical. Again, we found that you can’t do this in JUnit,

and the only way you can approximate the result is by using a convoluted

design pattern