Issue
I have an object that looks like this:
@Service
@ConditionalOnProperty(
name="name",
havingValue = "true"
)
public class MyClass{
@Autowired(required = false)
private SomeObject someObject;
}
And I have this in my test file:
@ExtendWith({SpringExtension.class})
@ContextConfiguration(classes = {MyClass.class}, loader = AnnotationConfigContextLoader.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MyTest {
MyClass myClass;
@Autowired
@ConditionalOnProperty(
name = "name",
havingValue = "true"
)
static MyClass getMyClass(){
return new MyClass();
}
}
@MockBean
static SomeObject someObject;
@BeforeAll
public void before() {
myClass = MyTest.getMyClass()
when(someObject.someFunc()).thenReturn(1);
}
}
I'm using this function because just using @Autowired and @MockBean on the SomeObject didn't work because of the @ConditionalOnProperty.
The problem is that inside MyClass, someObject is null.
Solution
No need to use static MyClass getMyClass()
use:
@ExtendWith({SpringExtension.class})
@ContextConfiguration(classes = {MyClass.class, SomeObject.class, loader = AnnotationConfigContextLoader.class)
@SpringBootTest(properties = "name=true")
public class MyTest{
@Autowired
MyClass
@Autowired myClass;
SomeObject someObject;
}
Answered By - Rony Tesler