[英]Unit testing with SpringJUnit4ClassRunner using only @Component and @Autowired
I have the following class: 我有以下课程:
@Component
public class MyClass {
@Autowired MyPojo pojo;
}
How do i test it without mocking the injected beans? 我如何在不模拟注入的豆子的情况下进行测试? I do not have a configuration [XML or declarative].
我没有配置[XML或声明性]。 I have done the following:
我已经完成以下工作:
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan
public class MyClassTest {
@Autowired MyClass myClass;
@Test
public void test() {
this.myClass...()
}
}
If you do not want use any type of configuration, neither Java nor XML config, you can use @ContextConfiguration
with your component classes listed: 如果不想使用任何类型的配置(Java或XML配置),都可以将
@ContextConfiguration
与列出的组件类一起使用:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MyPojo.class, MyClass.class })
public class MyClassTest {
@Autowired
private MyClass myClass;
@Test
public void test() {
// myClass...
}
}
Please note that MyPojo
class should also be annotated with @Component
. 请注意,
MyPojo
类也应使用@Component
进行注释。
However, in the real life scenario you probably will need at least one @Configuration
class (which can be also used with @ContextConfiguration
). 但是,在现实生活中,您可能至少需要一个
@Configuration
类(也可以与@ContextConfiguration
一起@ContextConfiguration
)。
Please refer Spring Documentation for more information about Spring integration tests support. 请参考Spring文档以获取有关Spring集成测试支持的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.