Home > database >  How to redefine spybean per test?
How to redefine spybean per test?

Time:07-07

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.

CodePudding user response:

@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);
}
  • Related