如何每次测试重新定义Spybean?

发布于 2025-02-13 09:47:22 字数 311 浏览 2 评论 0原文

我有一个带有Spybean的Springboott:

@SpyBean
private MyProperties myProperties;

我想测试MyProperties中不同值的组件的行为。但是,我注意到,当我在单个测试中更改myproperties的值时,下一个测试将在上一个测试中设置值,而当我尝试重置该值时:

@BeforeEach
void setUp() {
   myProperties = new MyProperties();
}

随后的单个测试变化无效。

I've got a SpringBootTest with a spyBean:

@SpyBean
private MyProperties myProperties;

I'd like to test the behaviour of the component under test with different values within myProperties. I have noticed, however, that when I change the values of myProperties in a single test, the next tests get the value set in the previous test and when I try to reset the value:

@BeforeEach
void setUp() {
   myProperties = new MyProperties();
}

The subsequent change in individual test has no effect.

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

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

发布评论

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

评论(1

痴者 2025-02-20 09:47:22

@mockbean@spybean在运行多个集成测试时,由春季上下文创建的实例上的模拟/间谍被缓存。解决此问题的一种方法是在下一个测试中添加@dirtiesContext,但不建议这样做,因为它会减慢您的测试。其他解决方案可以是使用myProperties使用ReflectionTestutils在下一个测试中

@BeforeEach
void setUp() {
    myProperties = new MyProperties();
    ReflectionTestUtils.setField(classInstance,"myProperties", myProperties);
}

@MockBean or @SpyBean mocks/spies on instance created by spring context and spring context is cached when running multiple integration tests. One way to fix this is to add @DirtiesContext on next test but this is not recommended as it will slow down your tests. Other solution could be to inject myProperties using ReflectionTestUtils in next test like this

@BeforeEach
void setUp() {
    myProperties = new MyProperties();
    ReflectionTestUtils.setField(classInstance,"myProperties", myProperties);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文