Replies: 1 comment
-
This was my hasty stab at trying to get something similar working: @Shared DetachedMockFactory mockFactory = new DetachedMockFactory()
@Shared MockUtil mockUtil = new MockUtil()
@Shared Map<String,Object> mockRegistry = [:]
public <T> T mockInjectedBeans(Specification spec, Class<T> beanType, List<String> toMock = []) {
T bean = context.getBean(beanType)
Field[] fields = beanType.getDeclaredFields()
fields.each { field ->
if (context.containsBean(field.name) && toMock.contains(field.name)) {
field.setAccessible(true)
Object injectable = context.getBean(field.name)
mockRegistry.put(field.name, injectable)
def mock = mockFactory.Mock(field.type)
mockUtil.attachMock(mock, spec)
field.set(bean, mock)
}
}
log.info("Mocked beans: ${mockRegistry.keySet().join(", ")}")
return bean
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
@SpringBean
annotation describes the following behavior:Unfortunately, on any sizable code base this quickly results in the ApplicationContext being reloaded frequently, causing our tests to take many times longer to run.
I tried wiring up some mechanism for dynamically auto-mocking beans on an object under test, and then restoring the original beans on
cleanup()
and thus avoiding dirtying the original Spring ApplicationContext, but I've had no luck in getting this working. Something similar to antoinemeyer/mock-in-bean.Would it be possible to improve upon
@SpringBean
to do something similar?Beta Was this translation helpful? Give feedback.
All reactions