dr.dreigh
04/06/2020, 12:28 PM@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@Component
class NormalComponent() {
fun value() = "Hi"
}
Test:
@TestConfiguration
class TestConfig {
@Bean
fun normalComponentMock(): NormalComponent {
val mock = mock(NormalComponent::class.java)
`when`(mock.value()).thenReturn("I AM A MOCK!")
return mock
}
}
@SpringBootTest
@Import(TestConfig::class)
class DemoApplicationTests(
@Autowired val norm: NormalComponent
) {
@Test
fun normInjectedIntoTest() {
assertEquals("I AM A MOCK!", norm.value())
}
}
The error:
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [com.example.demo.NormalComponent norm] in constructor [public com.example.demo.DemoApplicationTests(com.example.demo.NormalComponent)]: No qualifying bean of type 'com.example.demo.NormalComponent' available: expected single matching bean but found 2: normalComponent,normalComponentMock
I know I could use @MockBean
- this is just a simple example where the bean I want to inject to the instance.
Bit confused why the mock conflict is happening when I have using the @TestConfiguration
and the @Import
annotation - thanks in advance 🙏kqr
04/06/2020, 12:41 PMthanksforallthefish
04/06/2020, 12:45 PMNo qualifying bean of type 'com.example.demo.NormalComponent' available: expected single matching bean but found 2: normalComponent,normalComponentMock
thanksforallthefish
04/06/2020, 12:46 PMthanksforallthefish
04/06/2020, 12:48 PMclass NormalComponent
.eg
@Component
@ConditionalOnProperty(...)
class NormalComponent()
dr.dreigh
04/06/2020, 12:51 PMdoes not @SpringBootApplication componentScan, so that in your test you have your normal and mock beans?Yeah I think that is happening. If I put
@Primary
in the non-test Bean we don't get the test Mockbean injected into the testdr.dreigh
04/06/2020, 12:52 PM@Primary
...
expected: <I AM A MOCK!> but was: <Hi>dr.dreigh
04/06/2020, 12:53 PMJukka Siivonen
04/06/2020, 12:55 PMspring:
main:
allow-bean-definition-overriding: true
Jukka Siivonen
04/06/2020, 12:55 PMthanksforallthefish
04/06/2020, 12:56 PM@Primary
goes on your test beandr.dreigh
04/06/2020, 12:56 PMdr.dreigh
04/06/2020, 12:57 PMdr.dreigh
04/06/2020, 12:58 PMJukka Siivonen
04/06/2020, 1:00 PMdr.dreigh
04/06/2020, 1:00 PMdr.dreigh
04/06/2020, 1:01 PMthanksforallthefish
04/06/2020, 1:04 PM@Conditional
. there is a RestTemplateAutoConfiguration
that creates a default RestTemplateBuilder
, but that default one is annotated with @ConditionalOnMissingBean
. that means that if your application defines another RestTemplateBuilder
the one in your application is preferreddr.dreigh
04/06/2020, 1:04 PMthanksforallthefish
04/06/2020, 1:05 PM