测试 class 从数据库中插入、更新和删除

Testing class that insert, update and delete from the db

我 class 有 3 种方法:从数据库中插入、更新和删除。 为了在插入测试方法中测试它,我需要使用插入方法,在我插入之后我需要删除我插入的内容,但是为了删除我应该使用我也想测试的删除方法所以它没有'我需要使用它们并测试它们对我来说没有意义。

希望您能理解我的问题。提前致谢!

默认情况下,JUnit 不保证测试方法的顺序。尽管如此,从 JUnit 4.11 开始,您可以按测试名称排序,如下所示:

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Test1 {

    @Test
    public void aInsert() {
        System.out.println("first INSERT");
    }

    @Test
    public void bUpdate() throws Exception {
        System.out.println("second UPDATE");
    }

    @Test
    public void cDelete() throws Exception {
        System.out.println("third DELETE");
    }

}

您必须决定要测试什么。那是你描述的,它是一个集成测试。通过“真正的”单元测试,您只测试您的方法,而不是系统方法和数据库。

如果您想要单元测试,您有多种选择。例如,您使用接口并在语句到达数据库之前捕获它。

编辑 1 - 使用接口实现单元测试的一种可能性:

您需要一个接口来实现这些转到后端系统的方法:

public interface IDatabase{

    public returnValue insert(yourParam);

    public int update(yourParam);

}

然后你在 class:

中用真正的函数实现你的方法
public class Database implements IDatabase {

    @Override
    public returnValue insert(yourParam) {
        // do something
        return null;
    }

    @Override
    public int update(yourParam){
        // do something
        return 0;
    }    
}

这个class你在主class中调用:

/**
 * The real class to do what you want to do.
 */
public class RealClass {

private IDatabase dbInstance = null;

    private IDatabase getDbInstance() {
        if (dbInstance == null) {
            dbInstance = new Database();
        }
        return dbInstance;
    }

    protected void setDbInstance(IDatabase dataBase) {
        dbInstance = dataBase;
    }

    public static void main(String[] args) {
        getDbInstance().insert(yourParam);

    }
}

对于单元测试,您再次实现接口:

public class UnitTest implements IDatabase {

    @Override
    public returnValue insert(yourParam) {
        // Here can you test your statement and manipulate the return value
        return null;
    }

    @Override
    public int update(yourParam){
        if (yourParam.containsValue(value1)) {
          assertEquals("yourStatement", yourParam);
          return 1;
        }else if (yourParam.containsValue(value2)) {
          assertEquals("yourStatement2", yourParam);
          return 5;
        }else{
           assertTrue(false,"unknown Statement")
        }
    }

    @Test
    public void yourTest(){
       RealClass.setDbInstance(this);
        //Test something
    }        
}

这是time-consuming实现的,但是有了这个,你就独立于后端系统,你可以在没有数据库的情况下每次调用unittest。