Setting an instance variable in a Test Class
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Saturday, February 16, 2008 01:53 PM

When I run the following test: import static org.junit.Assert.*; import org.junit.Test; public class TestTest { private int i; @Test public void firstTest() { this.i = 1; assertEquals(1, this.i); } @Test public void secondTest() { assertEquals(1, this.i); } } it fails. When I debug it it seems that the instance variable is set back to default 0 between the tests. 1.) Why is that so? 2.) What is the recommended pattern to use if you do need to keep some state between two tests. E.g. test1 you test if a new object is succesfully persisted with a ORM tool.    More>>

When I run the following test:


			
import static org.junit.Assert.*;
import org.junit.Test;

public class TestTest {

private int i;

@Test
public void firstTest() {
this.i = 1;
assertEquals(1, this.i);
}

@Test
public void secondTest() {
assertEquals(1, this.i);
}
}


it fails. When I debug it it seems that the instance variable is set back to default 0 between the tests.


1.) Why is that so?

2.) What is the recommended pattern to use if you do need to keep some state between two tests.

E.g. test1 you test if a new object is succesfully persisted with a ORM tool. In this test you get the primary key . In following tests you need the primary key of this object e.g. to retrieve it again from the DB.

   <<Less

Re: Setting an instance variable in a Test Class

Posted By:   Robert_Lybarger  
Posted On:   Saturday, February 16, 2008 09:54 PM

I believe junit runs each test method in a different instance of the class, which is actually desirable to prevent effects of one test from influencing another. In your case, you could probably make 'i' a static variable, but the better solution for unit testing DB query code would be to create a database setup script that populates known-good material so that 'secondTest' has a better chance of being properly initialized when it runs, and does not depend on success/failure of firstTest. (Otherwise, you haven't really written two unit tests... you've written one test split improperly across two methods.)
About | Sitemap | Contact