java bootstrap 模拟 ConditionalOnProperty 和 Autowired 成员
java bootstrap mock with ConditionalOnProperty and Autowired member
我有一个看起来像这样的对象:
@Service
@ConditionalOnProperty(
name="name",
havingValue = "true"
)
public class MyClass{
@Autowired(required = false)
private SomeObject someObject;
}
我的测试文件中有这个:
@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);
}
}
我正在使用此功能,因为由于 @ConditionalOnProperty,仅在 SomeObject 上使用 @Autowired 和 @MockBean 不起作用。
问题是在 MyClass 中,someObject 为 null。
无需使用静态MyClass getMyClass()
使用:
@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;
}
我有一个看起来像这样的对象:
@Service
@ConditionalOnProperty(
name="name",
havingValue = "true"
)
public class MyClass{
@Autowired(required = false)
private SomeObject someObject;
}
我的测试文件中有这个:
@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);
}
}
我正在使用此功能,因为由于 @ConditionalOnProperty,仅在 SomeObject 上使用 @Autowired 和 @MockBean 不起作用。
问题是在 MyClass 中,someObject 为 null。
无需使用静态MyClass getMyClass()
使用:
@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;
}