java - 模拟 Spring 中许多类中常见的类实例

标签 java spring unit-testing junit

我对 Spring 概念很陌生。我正在尝试为该类的方法之一编写一个 Junit。我想模拟从多个位置用作 @Autowired 的 spring 框架 JdbcTemplate 类。但我不想在每个类中使用 @Mock 。有什么方法可以模拟这个类,并且可以通过使用 @Autowired 从多个位置使用它。

提前致谢。

最佳答案

定义一个特定于您的测试的 Spring 配置文件(例如“test”),在该配置文件中使用模拟库和注释 @Profile("test") 创建 JdbcTemplate bean。这样,只有当“测试”配置文件处于 Activity 状态时才会创建该模拟。

将注释@Profile("!test")添加到真实的JdbcTemplate bean中,这样就不会在测试配置文件中创建它。

然后在测试类顶部添加 @ActiveProfiles("test") 注释。

关于java - 模拟 Spring 中许多类中常见的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397329/

相关文章:

java - 重写CompoundPropertyModel中对象的getter方法

java - 错误预验证类 - Java/Eclipse/Blackberry

java - 将组合框重置为第一项

java - Netbeans dist jar 文件给出 NoClassDefFoundError

java - Pivotal tc Server v.3.1 无法启动

java - SpringBoot 2 与 Flyway : spring. Flyway.locations 被忽略

java - 如何在 Spring HandlerInterceptorAdapter 中将 header 添加到 http 响应?

c# - 如何模拟 ExceptionContext 以使用 .NET Core 3 Web API 和 Moq 进行测试

unit-testing - 如何对依赖于许多其他类的类进行单元测试?

c - 如何 stub 声明为 "extern void _x"的变量/函数