Running the Android SetUp () method is called several times

I am creating a test package 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 these tests created by the 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 them is called like this, musicDAO is regenerated. How can I stop the installation method call

+5
source share
3 answers

. JUnit , setUp() tearDown() . , , . , . , , , , .

+5

@BeforeClass @AfterClass 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();
}

. static

+1

. , setUp tearDown. , :

static int testsExecutedSoFar = 0;
static boolean isFirstRun = true;

@Override
protected void setUp() throws Exception {
    if(isFirstRun){
        createDb();
        isFirstRun = false;
    }       
}

@Override
protected void tearDown() throws Exception{
    testsExecutedSoFar++;
    if (testsExecutedSoFar == totalNumberOfTestCases())
        deleteDb();     
}

private int totalNumberOfTestCases() {
    return countTestCases()+1; //have to add one for testandroidtestcasesetupproperly added by AndroidTestCase
}

Fields must be static, as JUnit creates a new instance of the class for each run. Magic 1 needed to be added since AndroidTestCase adds its own test (testandroidtestcasesetupperly) to the test suite, but it does not take into account the number returned by countTestCases ().

A bit on the ugly side, but it did the trick.

0
source

All Articles