dimanche 11 avril 2021

How do I stop my DatabaseHelper test adding to the apps actual database?

I have built a contact app and am trying to learn to write tests. At the moment my TestAddContact passes, except every time I run it, it is actually adding the data to the apps database. How can I make it so the test does not add to the actual apps data?

package com.domscott.contactapplication;

import android.content.Context;
import android.database.Cursor;

import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.util.ArrayList;

import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
public class MyDatabaseHelperTest {

    private MyDatabaseHelper database;

    @Before
    public void setUp() throws Exception {
        database = new MyDatabaseHelper(ApplicationProvider.getApplicationContext());
    }
    @After
    public void tearDown() {
        database.close();
    }

    @Test
    public void TestAddContact() {

        ArrayList<String> idTest = new ArrayList<>();
        ArrayList<String> f_nameTest = new ArrayList<>();
        ArrayList<String> l_nameTest = new ArrayList<>();
        ArrayList<String> phoneTest = new ArrayList<>();

        database.addContact("dom","scott", "123");
        Cursor cursor = database.readData();
        while (cursor.moveToNext()) {
            idTest.add(cursor.getString(0));
            f_nameTest.add(cursor.getString(1));
            l_nameTest.add(cursor.getString(2));
            phoneTest.add(cursor.getString(3));

            Assert.assertEquals(f_nameTest.get(0), "dom");
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire