java - 如何测试使用外部包与数据库交互的方法

标签 java unit-testing junit mocking

我正在尝试测试一个函数,它是 struts 应用程序业务逻辑层的一部分。我面临问题,因为代码依赖于组织广泛使用的 jar 中的外部函数。

public CustomObject getCustomObject(String id){
        CustomObject customObject = new CustomObject();
        QueryObject sql = createSqlStatement(id); // EXTERNAL jar
        Result result = execute(sql); // EXTERNAL jar
        ArrayList list = result.getResulList(); // EXTERNAL jar

        // Logic to use the list object to fill the customObject
        // I can see an error here, that could have been 
        // caught in unit test

            return customObject ;
        }

现在的问题是测试填充对象的逻辑。
我编写的Junit4测试是:

    @Test
    public void testCustomObject()  {
        CustomObject customObjectwActual = new CustomObject();
        CustomObject customObjectExpected = new CustomObject();

           // set properties of customObjectExpected here

        customObjectwActual = getCustomObject(id); // Exception here

        assertEquals(customObjectExpected , customObjectwActual );
    }

抛出异常是因为根据开发人员的解释,“外部 jar 类是在 struts 应用程序启动时加载的”。我是 Java 和 struts 新手。我的做法有错吗?有没有办法以某种方式在 setUpBeforeClass() 中“加载”这些外部 jar 类?
如果有任何不清楚的地方,请告诉我。

编辑2: 抱歉,我的问题不清楚。我的类路径中有这些外部 jar 。它编译得很好,并且实际上加载了外部 jar 的类。 SQL 查询存储在 xml 文件中。这些外部 jar 也有自己的 xml 文件和 SQL 语句。无法加载这两个 xml 文件之一。
此外,即使它们正确加载,我实际上也不想调用数据库。有什么方法可以模拟这些调用吗?

最佳答案

Is there a way to "load" these external jar classes in the setUpBeforeClass() in someway?

您只需将这些 jar 包含在您的类路径中即可。当您使用类时,它们会在运行时自动加载

I am new to Java and struts. Is my approach wrong?

没有任何特定于 Struts 的内容。它是普通的核心java,您在项目中使用的外部类必须包含在您的类路径中

Is there some way to mock these calls?

如果你模拟这些调用,那么编写测试数据库交互的数据库测试用例有什么用

我还建议使用像 eclipse 这样的 IDE,因为它对开发非常有帮助,例如预先提供编译问题、格式化等

关于java - 如何测试使用外部包与数据库交互的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16381380/

相关文章:

java - 通过 SSL 连接 postgresql 时使用 "Verify-full"的开销

PHPUnit 数据提供者错误

unit-testing - 将 TDD 与 Web 应用程序开发集成的最佳实践?

java - @Value 在 junit 5 中为 null

java - 无法设置鼠标光标 JLayeredPane

java - 在thread_pool中始终始终搜索特定节点

.net - 是否有任何 .net 等同于 Rails 固定装置?

Java JUnit 测试

java - Selenium 3.0 ExpectedConditions 问题

java - 在 Java 中将十进制度或度分秒转换为米