java - eclipse junit 问题:"method initializationerror not found"

 qinyu1982_469 发布于 2022-11-06 06:21

创建了一个Junit Test Case 代码如下:

package com.example;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

public class Test {

    @org.junit.Test
    public void test() {

        System.out.println("hello");
    }

    /**
     * 编写一个通用的方法, 在不修改源程序的情况下, 可以获取任何数据库的连接
     * 解决方案: 把数据库驱动 Driver 实现类的全类名、url、user、password 放入一个
     * 配置文件中, 通过修改配置文件的方式实现和具体的数据库解耦. 
     * @throws Exception 
     */
    @org.junit.Test
    public Connection getConnection() throws Exception{
        String driverClass = null;
        String jdbcUrl = null;
        String user = null;
        String password = null;
        
        //读取类路径下的 jdbc.properties 文件
        InputStream in = 
                getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(in);
        driverClass = properties.getProperty("driver");
        jdbcUrl = properties.getProperty("jdbcUrl");
        user = properties.getProperty("user");
        password = properties.getProperty("password");
        
        //通过反射常见 Driver 对象. 
        Driver driver = 
                (Driver) Class.forName(driverClass).newInstance();
        
        Properties info = new Properties();
        info.put("user", user);
        info.put("password", password);
        
        //通过 Driver 的 connect 方法获取数据库连接. 
        Connection connection = driver.connect(jdbcUrl, info);
        
        return connection;
    }
    
    @org.junit.Test
    public void testGetConnection() throws Exception{
        System.out.println(getConnection());
    }
}

可是在方法上 右键 -- Run As -- JUnit Test 出现如下错误

出现如下提示框:

在网上查找: 说是因为缺少hamcrest的jar包, 导入后依然有上面的错误, 下面是我的工程的目录. junit.jar是 4.12 版本的.

这个问题怎么解决呢?

2 个回答
  • 你放的不对啊,Eclipse里给普通的java项目添加jar依赖通过如下步骤:

    2022-11-11 04:27 回答
  • 上图中:在JUnit4里面已经有了junit.jar, hamcrest依赖。
    lib文件夹里又有一个hamcrest依赖。

    现在是有了2个hamcrest的依赖,怀疑是冲突了,建议删除lib下的hamcrest试试

    2022-11-11 04:34 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有