如何在android中测试我的dbmanager类?

如何在android中测试我的dbmanager类?,android,android-testing,Android,Android Testing,在我的android应用程序中,我使用的是ormlite。现在我想为db助手方法创建一些测试用例。我不知道这应该如何正常工作。在具体测试开始之前,需要在我的测试用例中创建数据库。例如,我想测试是否会按预期创建用户。为此,我有一个addUser方法,应该进行测试,但如何才能做到这一点 目前,我为我的DBManager类创建了一个带有TestCase的TestProject 这是我的DBHelper类 public class DBHelper extends OrmLiteSqliteOpenHe

在我的android应用程序中,我使用的是ormlite。现在我想为db助手方法创建一些测试用例。我不知道这应该如何正常工作。在具体测试开始之前,需要在我的测试用例中创建数据库。例如,我想测试是否会按预期创建用户。为此,我有一个addUser方法,应该进行测试,但如何才能做到这一点

目前,我为我的DBManager类创建了一个带有TestCase的TestProject

这是我的DBHelper类

public class DBHelper extends OrmLiteSqliteOpenHelper{

    private static final String DATABASE_NAME = "pdixattach.db";
    private static final int DATABASE_VERSION = 4;
    private static final String TAG = DBHelper.class.getSimpleName();
    private static DBHelper _helperInstance;

    private Dao<Attachment, Integer> attachmentDao = null;
    private Dao<User, Integer> userDao = null;
    private Dao<Comment, Integer> commentDao = null;
    private Dao<Job, Integer> jobDao = null;
    private Dao<Target, Integer> targetDao = null;


    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource source) {
        Log.i(TAG, "onCreate");

        try{
            dropTables(source);
            TableUtils.createTable(source, Attachment.class);
            TableUtils.createTable(source, User.class);
            TableUtils.createTable(source, Comment.class);
            TableUtils.createTable(source, Target.class);
            TableUtils.createTable(source, Job.class);
            TableUtils.createTable(source, ConfigurationParameter.class);


        } catch (Exception e){
            Log.e(TAG, "error while creating tables "  + e.getMessage());
            throw new RuntimeException(e);
        }

    }

    @Override
    public void onUpgrade(final SQLiteDatabase db, final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
        Log.i(TAG, "onUpgrade");
        try {
            dropTables(connectionSource);
            onCreate(db, connectionSource);

        } catch (SQLException e) {
            Log.e(TAG, "error while upgrading tables " + e.getMessage());
            throw new RuntimeException(e);
        }

        // after we drop the old databases, we create the new ones
        onCreate(db, connectionSource);

    }

    private void dropTables(final ConnectionSource connectionSource)
            throws SQLException {

        TableUtils.dropTable(connectionSource, Attachment.class, true);
        TableUtils.dropTable(connectionSource, User.class, true);
        TableUtils.dropTable(connectionSource, Target.class, true);
        TableUtils.dropTable(connectionSource, Job.class, true);
        TableUtils.dropTable(connectionSource, Comment.class, true);
        TableUtils.dropTable(connectionSource, ConfigurationParameter.class, true);
    }



    public Dao<Attachment, Integer> getAttachmentDao() throws SQLException {
        if (this.attachmentDao == null) {
            this.attachmentDao = getDao(Attachment.class);
        }
        return this.attachmentDao;
    }

    public Dao<User, Integer> getUserDao() throws SQLException {
        if (this.userDao == null) {
            this.userDao = getDao(User.class);
        }
        return this.userDao;
    }

    public Dao<Comment, Integer> getCommentDao() throws SQLException {
        if (this.commentDao == null) {
            this.commentDao = getDao(Comment.class);
        }
        return this.commentDao;
    }

    public Dao<Target, Integer> getTargetDao() throws SQLException {
        if (this.targetDao == null) {
            this.targetDao = getDao(Target.class);
        }
        return this.targetDao;
    }

    public Dao<Job, Integer> getJobDao() throws SQLException {
        if (this.jobDao == null) {
            this.jobDao = getDao(Job.class);
        }
        return this.jobDao;
    }


    /**
     * Close the database connections and clear any cached DAOs.
     */
    @Override
    public void close() {
        super.close();
        _helperInstance = null;
        this.attachmentDao = null;
        this.commentDao = null;
        this.jobDao = null;
        this.targetDao = null;
        this.userDao = null;
    }
有人能帮我解决这个问题吗?我想,一旦第一次测试开始,其他测试就应该清楚了。
谢谢

@AI Phaba您能找到关于如何编写测试用例来测试DB方法的信息吗?事实上,我和你有同样的担忧,但在谷歌搜索了很多次后,还是找不到满意的答案。如果你有什么需要分享的,请帮助我。:)
public class DBManager {

private DBHelper helper;
private static DBManager uniqueInstance;
private static final String TAG = DBManager.class.getSimpleName();

public DBManager(Context context) {
    helper = new DBHelper(context);
}

public static void init(Context context) {
    if (uniqueInstance == null) {
        uniqueInstance = new DBManager(context);
    }
}

public static DBManager getInstance() {
    return uniqueInstance;
}

public boolean addUser(User u) {
    boolean retVal = false;
    if (u == null) {
        throw new IllegalArgumentException("user must not be null");
    }

    try {
        helper.getUserDao().create(u);
        retVal = true;
    } catch (SQLException e) {
        Log.e(TAG, "error while adding user to db " + e.getMessage());
    }

    return retVal;
}

public boolean addServiceEndpoint(String endpoint) {
    Log.d(TAG, "adding Service Endpoint " + endpoint);

    boolean retVal = false;
    if (endpoint == null) {
        throw new IllegalArgumentException("endpoint must not be null");
    }

    try {
        Target t = new Target(endpoint);
        int result = helper.getTargetDao().create(t);
        Log.d(TAG, "creating target entry resulted with value " + result);
        retVal = (result == 1);

    } catch (SQLException e) {
        Log.e(TAG,"error while adding target to db, with service endpoint " + endpoint + "error" + e.getMessage());

    }

    return retVal;

}

public List<Target> getAllTargets() {
    List<Target> retVal = new ArrayList<Target>();
    try {
        retVal = helper.getTargetDao().queryForAll();

    } catch (SQLException e) {
        Log.e(TAG,
                "error while retrieving service endpoints, error" + e.getMessage());
    }

    return retVal;
}

public User storeUser(String username, String hashedPw, Target target,
        boolean storeLogin) {

    User loggedInUser = null;
    int loginState = (storeLogin) ? 1 : 0;

    if (username == null || hashedPw == null || target == null) {
        throw new IllegalArgumentException(
                "cannot store login with empty/null values");
    }

    try {

        QueryBuilder<User, Integer> queryBuilder = helper.getUserDao().queryBuilder();
        Where<User, Integer> where = queryBuilder.where();
        where.eq(User.USERNAME, username)
                .and().eq(User.TARGET_ID, target.getServiceEndpoint());

        PreparedQuery<User> prepareStmt = queryBuilder.prepare();
        List<User> userList = helper.getUserDao().query(prepareStmt);


        if (userList.isEmpty()) {
            Log.d(TAG, "no user found with this name in the db, need to store it");
            User newUser = new User(username, hashedPw, target);
            newUser.setStored(loginState);
            addUser(newUser);

            userList = helper.getUserDao().query(prepareStmt);

            loggedInUser = userList.get(0);

        } else {
            Log.d(TAG, "found at least one user with username " + username  + " target " + target);
            for (User u : userList) {
                if (u.getPassword().equals(hashedPw)) {
                        Log.d(TAG, "password is equal to the one in db");
                } 
                else {
                    u.setPassword(hashedPw);
                }
                // setze diesen User als aktiv!
                u.setStatus(1);
                u.setStored(loginState);
                helper.getUserDao().update(u);
                loggedInUser = u;
            }
        }

    } catch (SQLException e) {
        Log.d(TAG, "error while storing login" + e.getMessage());
    }
    return loggedInUser;

}

public Comment addComment(Comment cmt) {
    Comment retVal = null;

    if (cmt == null) {
        throw new IllegalArgumentException("cannot create a comment entry in database without comment");
    }

    try {
        retVal = helper.getCommentDao().createIfNotExists(cmt);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return retVal;

}

public Attachment addAttachment(Attachment att) {

    if (att == null) {
        throw new IllegalArgumentException(
                "cannot create attachment entry in database without attachment");
    }

    Attachment dbAttach = null;
    try {
        dbAttach = helper.getAttachmentDao().createIfNotExists(att);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return dbAttach;
}

public Job addJob(Job job) {
    Job dbJob = null;

    if (job == null) {
        throw new IllegalArgumentException(
                "no job given, cannot create an entry");
    }


    try {
        QueryBuilder<Job, Integer> queryBuilder = helper.getJobDao()
                .queryBuilder();
        Where<Job, Integer> where = queryBuilder.where();
        if (job.getInstanceId() == null)
            where.isNull(Job.INSTANCE_ID);
        else
            where.eq(Job.INSTANCE_ID, job.getInstanceId());

        where.and().eq(Job.COMMENT_ID, job.getComment().getComment()).and()
                    .eq(Job.ATTACH_ID, job.getAtach().getAttUri()).and()
                    .eq(Job.STATUS, "0").and()
                    .eq(Job.TARGET_ID, job.getTarget().getServiceEndpoint());

        PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
        Log.d(TAG, "querystring is " + prepareStmt.getStatement());
        List<Job> jobList = helper.getJobDao().query(prepareStmt);

        if (jobList.isEmpty()) {
            Log.d(TAG, "no job with these parameters given, need to create one");

            Log.d(TAG, "job id is " + job.getId());

            dbJob = helper.getJobDao().createIfNotExists(job);
            Log.d(TAG, "dbJob id is " + dbJob.getId());

        } else {
            Log.d(TAG,
                    "job does already exists for this parameters, wont create new");
            dbJob = jobList.get(0);
            // hier comment und status usw updaten
        }
    } catch (SQLException e) {
        Log.d(TAG, "Exception during adding a job to db: " + e.getMessage());
    }

    return dbJob;

}

public void attachInstanceIdToJob(String instanceId, long jobId) {
    Log.d(TAG, "attaching instance id " + instanceId + " to job with id " + jobId);

    try {
        Job job = helper.getJobDao().queryForId((int) jobId);
        if (job != null){
            job.setInstanceId(instanceId);
            helper.getJobDao().update(job);
        }

    } catch (NumberFormatException e) {


        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
            Log.d(TAG, "error while attaching instance id " + instanceId + " to job with id " + jobId);
    }


}

public List<Job> getAllOpenJobs() {
    List<Job> jobList = null;

    QueryBuilder<Job, Integer> queryBuilder;
    try {
        queryBuilder = helper.getJobDao()
                .queryBuilder();
    Where<Job, Integer> where = queryBuilder.where();
        where.eq(Job.STATUS, JobStatusEnum.OPEN.getState())
        .or().eq(Job.STATUS, JobStatusEnum.RETRY.getState());
        ;

    PreparedQuery<Job> prepareStmt = queryBuilder.prepare();
    Log.d(TAG, "querystring is " + prepareStmt.getStatement());
    jobList = helper.getJobDao().query(prepareStmt);


    } catch (SQLException e) {
        Log.d(TAG, "error while retrieving open jobs from db" + e.getMessage());
    }
    return jobList;
}

public void getDataForJob(Job j, User u, Attachment att, Target target, Comment comment) {
    try {
        if (j != null){
            helper.getUserDao().refresh(j.getUser());
            helper.getAttachmentDao().refresh(j.getAtach());
            helper.getTargetDao().refresh(j.getTarget());
            helper.getCommentDao().refresh(j.getComment());
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}


public User getCurrentStoredUser(){

    try {
        List<User> users = helper.getUserDao().queryForAll();
        for (User u: users){
            if (u.getStored() == 1){
                return u;
            }
        }


    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

public void updateJob(Job j) {

    if (j != null){
        try {
            helper.getJobDao().update(j);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
/**
 * The status of the given user will be configured to stored. All others will be set to unstored
 * @param loggedInUser
 */
public void setUserStatusToStored(User loggedInUser) {
    List<User> listOfUsers;
    try {
        listOfUsers = helper.getUserDao().queryForAll();

        for (User u: listOfUsers){
            if (u.equals(loggedInUser)){
                u.setStatus(UserStatusEnum.STORED.getState());
            }
            else{
                u.setStatus(UserStatusEnum.UNSTORED.getState());
            }

            helper.getUserDao().update(u);
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }           
}
}
public class DBManagerTest
    extends TestCase
{

protected void setUp() throws Exception {
    super.setUp();
}

protected void tearDown() throws Exception {
    super.tearDown();
}

public void testDBManager() {
    fail( "Not yet implemented" );
}
}