You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java作业中addPost与getPost方法JUnit测试失败求助

Java作业测试问题修复建议

现有代码结构

User类属性

private String userName, password;
private final Instant registrationDate;
private HashSet<User> setSubs;
private ArrayList<Post> listPosts;
private int Index;

User类核心方法

public Post addPost(String msg) {
    Post post = new Post(msg);
    listPosts.add(0, post);
    Index++;
    return post;
}
public Post getPost(int i) {
    return listPosts.get(i);
}

Post类属性

private final String textPost; 
private final Instant dateCreation; //this.dateCreation = Instant.now();
private HashSet<User> likedUsers;

遇到的问题

  1. addPost方法测试失败
    错误信息:org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
    失败断言代码:

    for (int i = 0; i < (self.getPostNb() - 1); i++) { //getPostNb() = listPost.size()
        assertTrue(self.getPost(i).isAfter(self.getPost(i + 1)));
    }
    
  2. getPost方法测试触发前置错误
    错误信息:java.lang.IllegalArgumentException: bound must be positive

修复方案

问题1:帖子日期顺序断言失败

问题本质:快速创建帖子时,Instant.now()可能返回相同时间戳,导致新帖和旧帖日期无先后;或Post类的isAfter方法逻辑错误。

修复步骤:

  • 验证并修正Post类的isAfter方法逻辑:
    public boolean isAfter(Post other) {
        return this.dateCreation.isAfter(other.dateCreation);
    }
    
  • 确保新帖时间严格晚于已有帖子,修改addPost方法(需给Post添加带时间参数的构造方法):
    // Post类新增构造方法
    public Post(String textPost, Instant dateCreation) {
        this.textPost = textPost;
        this.dateCreation = dateCreation;
        this.likedUsers = new HashSet<>();
    }
    
    // 保留原构造方法兼容现有代码
    public Post(String textPost) {
        this(textPost, Instant.now());
    }
    
    // 修改User类的addPost方法
    public Post addPost(String msg) {
        Instant postDate = listPosts.isEmpty() ? Instant.now() : 
            listPosts.get(0).dateCreation.plusNanos(1);
        Post post = new Post(msg, postDate);
        listPosts.add(0, post);
        Index = listPosts.size(); // 同步Index与列表长度
        return post;
    }
    

问题2:getPost触发bound must be positive错误

问题本质:Index变量与listPosts.size()不同步,或listPosts未初始化导致测试时用0作为随机数边界;或测试调用getPost时传入非法索引。

修复步骤:

  1. 初始化User类的listPosts和Index:
    public User(...) {
        // 其他属性初始化
        this.listPosts = new ArrayList<>();
        this.Index = 0;
    }
    
  2. 确保Index与listPosts.size()严格同步(移除冗余的Index或每次更新列表后同步):
    如上述addPost修改中,用Index = listPosts.size()替代单纯递增。
  3. 给getPost添加索引合法性校验,避免非法索引触发原生异常:
    public Post getPost(int i) {
        if (i < 0 || i >= listPosts.size()) {
            throw new IllegalArgumentException("Post index out of bounds: " + i);
        }
        return listPosts.get(i);
    }
    

内容的提问来源于stack exchange,提问作者Absentia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 13:42:44