奇怪的Mockito验证失败

huangapple go评论83阅读模式
英文:

Strange Mockito verify fail

问题

我正在使用Mockito测试我的Java应用程序,一切都很好,直到出现这个奇怪的失败测试。

如你所见,这一行末尾有一个额外的空格。

这是我的createUser方法:

@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
    try {
        User _user = userRepository.save(new User(user.getName()));
        return new ResponseEntity<>(_user, HttpStatus.CREATED);
    }
    catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

还有我的UserRepository:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findAll();
    List<User> findByName(String name);
}

我尝试搜索相关内容,但没有找到任何相关的结果。如果有人能帮我找到相关的帖子,我将不胜感激。

英文:

I am testing my java app with Mockito, all good until this strange fail test.
奇怪的Mockito验证失败
As you can see there is an extra blank space at the end of the line.

This is my createUser method.

    @PostMapping(&quot;/users&quot;)
    public ResponseEntity&lt;User&gt; createUser(@RequestBody User user) {
        try {
            User _user = userRepository.save(new User(user.getName()));
            return new ResponseEntity&lt;&gt;(_user, HttpStatus.CREATED);
        }
        catch (Exception e) {
            return new ResponseEntity&lt;&gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

And my UserRepository :

public interface UserRepository extends JpaRepository&lt;User, Long&gt; {
    List&lt;User&gt; findAll();
    List&lt;User&gt; findByName(String name);
}

I tried to search for this but nothing related found, if someone can help me with a related post.

答案1

得分: 0

在这行代码中 User _user = userRepository.save(new User(user.getName())); 创建了一个新的 User 实例。

很可能在 User 类中没有自定义的 equals 实现,默认情况下,如果两个不同的实例包含相同的数据,equals 方法会返回 false。

解决方法有三种:

  1. 将 user 原样传递给 repository.save,不创建新的实例。
  2. 在 User 类中定义 equals 方法,使其基于 name 字段进行比较。
  3. 使用 ArgumentCaptor 更新断言,然后验证捕获的对象。
英文:

In line User _user = userRepository.save(new User(user.getName())); new instance of User is created.

Mostly likely there is no custom equals implementation in User class - and as by default it would return false for 2 different instances, even if they contain same data.

3 ways to solve:

  1. pass user as-is into repository.save, without creating new instance
  2. define equals on User class to be equals on name field
  3. Update assertion to capture (using ArgumentCaptor) and then verify captured object

huangapple
  • 本文由 发表于 2023年8月9日 03:03:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定