mockito - 如何在 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;
}
解决方案
推荐阅读
- linux - 如何理解这个 Linux 排序输出
- c++ - Binary Search Tree leaf count issue
- rabbitmq - 获取向队列/交换发送消息的生产者的 IP
- html - 无法使用引导程序实现自定义网格布局
- algorithm - 设计一个数据结构来检索热门关键词
- react-native - 徽章不适合反应原生的底部导航
- sql - MS Excel:在 VBA 中使用 Shell 将 SSIS 包作为工作表中的嵌入对象运行
- matrix - 旋转矩阵,为什么它不能作为函数工作,但它可以在行命令中工作?
- gpu - tensorflow-serving batching_config.txt中的“max_batch_size”是什么意思?
- linux - 如何恢复损坏的 dnf 数据库?