[英]Why @Autowired raises UnsatisfiedDependencyException, even the class does not implement any interface?
Here is the class I want to test这是我要测试的 class
@Component
public class PermissionCheck {
@Autowired
private MyEntityRepository myEntityRepository;
public boolean hasPermission(int myEntityID) {
MyEntity myEntity = myEntityRepository.findById(myEntityId);
return myEntity != null;
}
}
Here is the test class这里是测试 class
@RunWith(SpringRunner.class)
public class PermissionCheckTests {
@Autowired // you need to autowire
private PermissionCheck permissionCheck; // and it uses @MockBean dependency
@MockBean // if no such @MockBean exists
private MyEntityRepository myEntityRepository; // the real implementation is used
@Test
public void shouldHasPermission() {
MyEntity myEntity = new MyEntity();
when(this.myEntityRepository.findById(any())).thenReturn(myEntity);
assertTrue(this.permissionCheck.hasPermission(0));
}
}
And when I run this test I got当我运行这个测试时,我得到了
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'PermissionCheckTests':
Unsatisfied dependency expressed through field 'permissionCheck';
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'PermissionCheck' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true),
@org.springframework.beans.factory.annotation.Qualifier(value="")}
From other SO questions, such as this one , I see that this happens when the target class implements an interface.从其他 SO 问题(例如这个问题)中,我看到当目标 class 实现接口时会发生这种情况。 But as we can see from the code,
PermissionCheck
does not implement any interface, so why is the exception still thrown?但是从代码中我们可以看出,
PermissionCheck
没有实现任何接口,那为什么还是抛出异常呢?
Does that mean I have to create an interface, @Autowired it and let PermissionCheck
implement it?这是否意味着我必须创建一个接口,@Autowired 并让
PermissionCheck
实现它? It seems redundant to me, since I don't see why I need such an interface.这对我来说似乎是多余的,因为我不明白为什么我需要这样的接口。 Is there a way to make it work without creating a new interface which I will solely use for this purpose?
有没有办法让它工作而无需创建我将仅用于此目的的新界面?
@RunWith(SpringRunner.class)
does not automatically load your configurations/beans/properties unless accompanied with annotations that specifically do that, such as @ContextConfiguration
and @TestPropertySource
. @RunWith(SpringRunner.class)
不会自动加载您的配置/beans/properties,除非附带专门执行此操作的注释,例如@ContextConfiguration
和@TestPropertySource
。
If yours is a Spring Boot application and you want to load the whole context along with all properties, you can simply add the @SpringBootTest
annotation to your test class.如果您的应用程序是 Spring 引导应用程序并且您想要加载整个上下文以及所有属性,您可以简单地将
@SpringBootTest
注释添加到您的测试 class 中。
References:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.