首页 > 解决方案 > 如何在 MockBean 的 Repository 中调用真正的保存方法?

问题描述

我有一个使用@MockBean 注释的存储库,但是我想调用真正的保存函数来保存实体,但是,即使我使用 CALLS_REAL_METHODS 它仍然不起作用,就像下面的代码一样:

@SpringBootTest
class SchoolTest {
  @MockBean StudentRepository studentRepository;
  
  @Test
  void studentRepository_throwConstraintViolationException_ifDuplicate() {
    studentRepository = mock(StudentRepository.class, CALLS_REAL_METHODS);

    Student student = new Student(12306L, "JinPing");
    studentRepository.save(student);

    Student student2 = new Student(12306L, "JinPing");

    assertThrows(ConstraintViolationException.class, ()-> studentRepository.save(student2));
  }
}

这是存储库

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

这是学生实体

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "student")
public class Student {
  @Id private Long id;

  private String name;
}

标签: mockitorepository

解决方案


推荐阅读