用于春季启动中所有Junit测试的模拟豆
在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您在主要来源中使用
@springbootapplication
来定义Spring Boot应用程序,则您已经对该软件包中的所有内容(包括嵌套软件包)中的所有内容都启用了组件扫描。运行测试时,也将SRC/Test/Java中的类(通常)添加到类Path,因此也可以扫描。
例如,如果您定义了
@springbootapplication
com.example.boot.boot.myspringbootapplication com.example.boot.mytestconfiguration 对于组件扫描,即使前者在SRC/MAIN中,后者在SRC/测试中。将其放入SRC/test/Java目录中,将确保在运行测试时仅具有效果。然后,您可以在该配置中定义您想要的任何“全局”豆。
使用我提供的软件包/类名称:
然后,只要您不从上下文配置中省略该配置,就应始终在测试中使用无名为。
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
atcom.example.boot.MySpringBootApplication
, thencom.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:
Then, so long as you don't omit that Configuration from the Context Configuration, the MockBean should always be present under test.