Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Android Tests setUp() method gets called multiple times

I am creating a test suite for my android application and have this setUp method

    private static final String TAG_NAME = "TESTING_SUITE";
        public TestingMusicDAO musicDAO;
        public List<Song> songs;
        public Instrumentation instr;
        MusicService musicService;
    @Override
    public void setUp() throws Exception {
        instr = this.getInstrumentation();
        Log.d(TAG_NAME, "Setting up testing songs");
        musicDAO = new TestingMusicDAO(instr.getContext());
        musicService = new MusicServiceImpl(musicDAO);
        musicDAO.getAllSongsFromFile();
        songs = musicDAO.getAllSongs();
        for(Song song : songs)
            Log.d( TAG_NAME, song.toString() );
     }

And then have these tests which are created by a python tool from a text file

public void test1() {
    List<Song> testPlaylist;
    String testArtist = ("The Beatles");
    String actualArtist = ("TheBeatles"); 
    testPlaylist = testingPlaySongsByKeyword(testArtist);
    if(testPlaylist.isEmpty()){
        fail("No Songs Were Found");
    } else {
        for( Song loopsongs : testPlaylist){
            if (!(loopsongs.getArtist().equals(actualArtist))){
                fail("Song Doesnt Contain the artist" + actualArtist + "... Contains ->" + loopsongs.getArtist());
            }
        }
   }
}

and every time one of these gets called the musicDAO is regenerated. How can I stop the setup method from being called

like image 287
Peter Djeneralovic Avatar asked Feb 05 '13 21:02

Peter Djeneralovic


2 Answers

You don't. The design of JUnit is that setUp() and tearDown() are done once per test. If you want it done per class, do it in the constructor. Just make sure that you don't alter anything inside the classes. The reason for doing it once per test is to make sure all tests start with the same data.

like image 136
Gabe Sechan Avatar answered Oct 13 '22 23:10

Gabe Sechan


You could use @BeforeClass and @AfterClass annotations from JUnit.

@BeforeClass
public static void test_setUp_Once(){
  // Code which you want to be executed only once
  createDb();
}

@AfterClass
public static void test_tearDown_Once(){
  // Code which you want to be executed only once
  deleteDb();
}

Note: You need to declare these methods static to work properly.

like image 20
Vikash Kumar Verma Avatar answered Oct 13 '22 22:10

Vikash Kumar Verma