[英]How to test dependency injection with annotations?
In Spring Framework or Java EE there are annotation based Dependency Injection.在 Spring 框架或 Java EE 中有基于注解的依赖注入。
Normally you would do通常你会做
class X
{
Y var;
public X(Y var)
{
this.var = var
}
}
This is so easy to test and mock.这很容易测试和模拟。 You just instantiate class Y as you like for your test.
您只需根据您的测试需要实例化 class Y 即可。
But how about this.但是这个怎么样。
class X
{
@Inject or @Autowired
Y var;
public X( )
{
}
}
How about annotation based Dependency Injection.基于注释的依赖注入怎么样。 You have the same problem as with hard coded instatiation.
您遇到与硬编码实例化相同的问题。 I have no possiblity to inject a mocked object as I could in the first code example.
我无法像在第一个代码示例中那样注入模拟的 object。 How can I test it?
我该如何测试它?
I have no possiblity to inject a mocked object as I could in the first code example
我无法像在第一个代码示例中那样注入模拟的 object
Why is that?这是为什么?
@Component
class X {
Y var;
@Autowired
public X(Y var)
{
this.var = var
}
@Component
class Y {
}
And then接着
@RunWith(SpringRunner.class)
public class ApiControllerTest {
@Autowired
private X x;
@Configuration
static class Config {
@MockBean
private Y y;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.