用于春季启动中所有Junit测试的模拟豆

发布于 2025-01-29 18:23:44 字数 96 浏览 2 评论 0原文

在Spring Boot中,是否有一种方法可以为所有现有的JUNIT测试模拟单个BEAN,而无需更改现有的测试类(例如,通过添加注释或添加继承)?就像通过配置在全球注入豆子一样。

In Spring Boot, is there a way to mock a single bean for all existing JUnit tests, without changing the existing test classes (e.g., by adding an annotation or adding inheritance)? Like injecting a bean globally via configuration.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流绪微梦 2025-02-05 18:23:44

假设您在主要来源中使用@springbootapplication来定义Spring Boot应用程序,则您已经对该软件包中的所有内容(包括嵌套软件包)中的所有内容都启用了组件扫描。

运行测试时,也将SRC/Test/Java中的类(通常)添加到类Path,因此也可以扫描。

例如,如果您定义了@springbootapplication com.example.boot.boot.myspringbootapplication com.example.boot.mytestconfiguration 对于组件扫描,即使前者在SRC/MAIN中,后者在SRC/测试中。将其放入SRC/test/Java目录中,将确保在运行测试时仅具有效果。

然后,您可以在该配置中定义您想要的任何“全局”豆。

使用我提供的软件包/类名称:

// File: src/test/java/com/example/boot/MyTestConfiguration.java

@Configuration // this will get component-scanned
public class MyTestConfiguration {

    @MockBean
    MyBean myGlobalMockBean;
}

然后,只要您不从上下文配置中省略该配置,就应始终在测试中使用无名为。

Assuming you are using @SpringBootApplication in your main sources to define the Spring Boot application, you'll already have component scanning enabled for everything in that package (including nested packages).

When running tests, the classes (typically) in src/test/java are also added to the classpath, and are therefore available to be scanned as well.

For example, if you defined your @SpringBootApplication at com.example.boot.MySpringBootApplication, then com.example.boot.MyTestConfiguration would be eligible for component scanning, even though the former is in src/main and the latter in src/test. Putting it in the src/test/java directory would ensure that it only has an effect while running tests.

You can then define any "global" beans you would like in that configuration.

Using the package/class names I provided:

// File: src/test/java/com/example/boot/MyTestConfiguration.java

@Configuration // this will get component-scanned
public class MyTestConfiguration {

    @MockBean
    MyBean myGlobalMockBean;
}

Then, so long as you don't omit that Configuration from the Context Configuration, the MockBean should always be present under test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文