Java assertEquals 导致 JUnit 测试失败

如何解决Java assertEquals 导致 JUnit 测试失败

我正在 Netbeans 中处理一个 java jdbcTemplate 项目,但我无法弄清楚我的 equals 和 hashcode 方法覆盖了我的 Dao 的 assertEquals 测试有什么问题。我被告知我需要对对象进行“深度比较”,但从我所见,我的代码已经在这样做了。以下是我涉及这个问题的不同课程

这是我的 Organization.class:

public class Organization {

    private int orgId;
    private String orgName;
    private String orgDescription;
    private String orgEmail;
    private String orgPhone;
    private Location orgLocation;

    
    
    
    public int getOrgId() {
        return orgId;
    }

    public void setOrgId(int orgId) {
        this.orgId = orgId;
    }

    public String getOrgName() {
        return orgName;
    }

    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }

    public String getOrgDescription() {
        return orgDescription;
    }

    public void setOrgDescription(String orgDescription) {
        this.orgDescription = orgDescription;
    }

    public String getOrgEmail() {
        return orgEmail;
    }

    public void setOrgEmail(String orgEmail) {
        this.orgEmail = orgEmail;
    }

    public String getOrgPhone() {
        return orgPhone;
    }

    public void setOrgPhone(String orgPhone) {
        this.orgPhone = orgPhone;
    }

    public Location getOrgLocation() {
        return orgLocation;
    }

    public void setOrgLocation(Location orgLocation) {
        this.orgLocation = orgLocation;
    }

    
    
    @Override
    public int hashCode() {
        int hash = 7;
        hash = 67 * hash + this.orgId;
        hash = 67 * hash + Objects.hashCode(this.orgName);
        hash = 67 * hash + Objects.hashCode(this.orgDescription);
        hash = 67 * hash + Objects.hashCode(this.orgEmail);
        hash = 67 * hash + Objects.hashCode(this.orgPhone);
        hash = 67 * hash + Objects.hashCode(this.orgLocation);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Organization other = (Organization) obj;
        if (this.orgId != other.orgId) {
            return false;
        }
        if (!Objects.equals(this.orgName,other.orgName)) {
            return false;
        }
        if (!Objects.equals(this.orgDescription,other.orgDescription)) {
            return false;
        }
        if (!Objects.equals(this.orgEmail,other.orgEmail)) {
            return false;
        }
        if (!Objects.equals(this.orgPhone,other.orgPhone)) {
            return false;
        }
        if (!Objects.equals(this.orgLocation,other.orgLocation)) {
            return false;
        }
        return true;
    }
    
}

这是我的组织道实现:

public class OrgDaoDBImpl implements OrgDao{
    
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    
    //ORGANIZATIONS - PREPARED STATEMENTS
    
    private static final String SQL_INSERT_ORGANIZATION
            = "insert into `organization` (org_name,org_description,org_email,"
            + "org_phone,location_id) "
            + "values (?,?,?)";

    private static final String SQL_DELETE_ORGANIZATION
            = "delete from `organization` where org_id = ?";

    private static final String SQL_UPDATE_ORGANIZATION
            = "update `organization` set org_name = ?,org_description = ?,org_email = ?,"
            + "org_phone = ?,location_id = ? "
            + "where org_id =  ?";

    private static final String SQL_SELECT_ORGANIZATION
            = "select * from `organization` where org_id = ?";

    private static final String SQL_SELECT_ALL_ORGANIZATIONS
            = "select * from `organization`";
    

    
    private static final String SQL_SELECT_LOCATION_BY_ORG_ID
            = "select l.location_id,l.loc_name,l.loc_street_address,"
            + "l.loc_city,l.loc_state,l.loc_zip_code,l.loc_lat,l.loc_long " 
            + "from location l "
            + "join organization o on l.location_id = o.location_id  " 
            + "where o.org_id = ?";
 
    @Override
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void addOrganization(Organization organization) {
        jdbcTemplate.update(SQL_INSERT_ORGANIZATION,organization.getOrgName(),organization.getOrgDescription(),organization.getOrgPhone(),organization.getOrgEmail(),organization.getOrgLocation().getLocationId());
            organization.setOrgId(
                    jdbcTemplate.queryForObject("select LAST_INSERT_ID()",Integer.class));
            
    }

    @Override
    public void deleteOrganization(int organizationId) {
        jdbcTemplate.update(SQL_DELETE_ORGANIZATION,organizationId);
    }

    @Override
    public void updateOrganization(Organization organization) {
        jdbcTemplate.update(SQL_UPDATE_ORGANIZATION,organization.getOrgLocation().getLocationId());
    }

    @Override
    public Organization getOrganizationById(int id) {
        try {
            Organization org = jdbcTemplate.queryForObject(SQL_SELECT_ORGANIZATION,new OrgMapper(),id);
            org.setOrgLocation(findLocationForOrganization(org));
            return org;
        } catch (EmptyResultDataAccessException ex) {
            return null; 
            }
    }

    @Override
    public List<Organization> getAllOrganizations() {
        return jdbcTemplate.query(SQL_SELECT_ALL_ORGANIZATIONS,new OrgMapper());
    }

    @Override
    public List<Organization> getAllOrgsBySupeId(int supeId) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods,choose Tools | Templates.
    }
    
    
    /////////////////////
    //*HELPER METHODS*//
    //***************//   
    
    //FIND Location associated with an organization
    private Location findLocationForOrganization(Organization org) {
        return jdbcTemplate.queryForObject(SQL_SELECT_LOCATION_BY_ORG_ID,new LocationMapper(),org.getOrgId());
    }

    
    //ASSOCIATE the location with the org entry
    private List<Organization>associateLocationWithOrg(List<Organization> orgList) {
        // set the complete list of author ids for each book
        for (Organization currentOrg : orgList) {
            // add the Location to current Org
            currentOrg.setOrgLocation(findLocationForOrganization(currentOrg)); }
        return orgList; 
    }
    
    
    /////////////
    //*MAPPERS*/
    //*******//
    
    private static final class OrgMapper implements RowMapper<Organization> {
        
        @Override
        public Organization mapRow(ResultSet rs,int i) throws SQLException {
            Organization org = new Organization();
            org.setOrgId(rs.getInt("org_id"));
            org.setOrgName(rs.getString("org_name"));
            org.setOrgDescription(rs.getString("org_description"));
            org.setOrgPhone(rs.getString("org_phone"));
            org.setOrgEmail(rs.getString("org_email"));
            
              
            
            return org;
        
        }    
    }
    
    private static class LocationMapper implements RowMapper<Location>{
        
        @Override
        public Location mapRow(ResultSet rs,int i) throws SQLException {
            Location loc = new Location();
            loc.setLocationId(rs.getInt("location_id"));
            loc.setLocName(rs.getString("loc_name"));
            loc.setLocStreetAddress(rs.getString("loc_street_address"));
            loc.setLocCity(rs.getString("loc_city"));
            loc.setLocState(rs.getString("loc_state"));
            loc.setLocZipCode(rs.getString("loc_zip_code"));
            loc.setLocLat(rs.getString("loc_lat"));
            loc.setLocLong(rs.getString("loc_long"));

            
            return loc;
        }
    }
}

My Organization.class 使用 Location 对象来输入额外的位置信息。所以在下面,我首先必须在尝试添加组织之前添加一个位置。目前,添加位置测试成功。

public class SuperSighting_DaoTests {
    
    LocationDao ldao;
    OrgDao odao;
    PowerDao pdao;
    SightingDao sidao;
    SupeDao sudao;
    
    public SuperSighting_DaoTests() {
    }
    
    @BeforeClass
    public static void setUpClass() {
    }
    
    @AfterClass
    public static void tearDownClass() {
    }
    
    @Before
    public void setUp() {
        ApplicationContext ctx
        = new ClassPathXmlApplicationContext("test-applicationContext.xml");
            
            ldao = ctx.getBean("LocationDao",LocationDao.class);
            odao = ctx.getBean("OrgDao",OrgDao.class);
            pdao = ctx.getBean("PowerDao",PowerDao.class);
            sidao = ctx.getBean("SightingDao",SightingDao.class);
            sudao = ctx.getBean("SupeDao",SupeDao.class);
            
            // delete all supes
            List<Supe> supes = sudao.getAllSupes(); for (Supe currentSupe : supes) {
            sudao.deleteSupe(currentSupe.getSupeId()); 
            }
            // delete all powers
            List<Power> powers = pdao.getAllPowers(); for (Power currentPower : powers) {
            pdao.deletePower(currentPower.getPowerId()); 
            }
            //delete all organizations
            List<Organization> orgs = odao.getAllOrganizations(); for (Organization currentOrg : orgs) {
            odao.deleteOrganization(currentOrg.getOrgId()); 
            }
            // delete all locations
            List<Location> locations = ldao.getAllLocations(); for (Location currentLocation : locations) {
            ldao.deleteLocation(currentLocation.getLocationId()); 
            }
            // delete all sightings
            List<Sighting> sightings = sidao.getAllSightings(); for (Sighting currentSighting : sightings) {
            sidao.deleteSighting(currentSighting.getSightingId()); 
            }
    }
    @Test
    public void testAddGetOrganization() {
        
        Location loc = new Location();
        loc.setLocName("Legion of Doom");
        loc.setLocStreetAddress("127 Taco St.");
        loc.setLocCity("Smalltown");
        loc.setLocState("MA");
        loc.setLocZipCode("19698");
        loc.setLocLat("39.16567925978815");
        loc.setLocLong("-75.59452746539126");
        
        ldao.addLocation(loc);
    
        Organization org = new Organization();
        org.setOrgName("Legion of Doom");
        org.setOrgDescription("evil organization");
        org.setOrgPhone("333-444-5678");
        org.setOrgEmail("lod@evil.org");
        org.setOrgLocation(loc);
        
        odao.addOrganization(org);

 
        
        Organization fromDao = odao.getOrganizationById(org.getOrgId());
        fromDao.toString();

        assertEquals(fromDao,org);
    
    }

当测试完成时,我可以看到比较的项目完全相同,但测试失败并给我这个错误:

测试运行:8,失败:1,错误:0,跳过:0,经过的时间:2.931 秒

以下图片显示了被比较的两个对象('org' 和 'fromDao')的字段值:two object being compared

我真的不确定从哪里开始,因为我的最终目标依赖于测试的通过。我已经多次浏览代码,除了重写整个程序之外,我不知道该怎么做。任何建议表示赞赏,因为我仍然是新手!谢谢!

解决方法

已删除:完全错误 - 应该更仔细地检查屏幕截图

,

我想删除这个问题,但我不能。 -感谢您的快速回复!

我以某种方式解决了这个问题......实际上,我的手机和电子邮件正在检索 - 您可以在屏幕截图中看到这一点......经过数小时的凝视后很容易错过。

我检查了所有代码并切换了顺序以匹配数据库,现在我的测试都是绿色的。

再次感谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res