为什么@Autowired引发UnsatisfiedDependencyException,即使该类未实现任何接口? [英] Why @Autowired raises UnsatisfiedDependencyException, even the class does not implement any interface?
问题描述
这是我要测试的课程
@Component
public class PermissionCheck {
@Autowired
private MyEntityRepository myEntityRepository;
public boolean hasPermission(int myEntityID) {
MyEntity myEntity = myEntityRepository.findById(myEntityId);
return myEntity != null;
}
}
这是考试班
@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="")}
从其他SO问题(例如此问题)中,我看到发生了这种情况当目标类实现接口时.但是,从代码中可以看到, PermissionCheck
没有实现任何接口,那么为什么仍然抛出异常?
From other SO questions, such as this one, I see that this happens when the target class implements an interface. But as we can see from the code, PermissionCheck
does not implement any interface, so why is the exception still thrown?
这是否意味着我必须创建一个接口,@Autowired接口,然后让 PermissionCheck
实现它?对我来说似乎是多余的,因为我不明白为什么需要这样的界面.有没有一种方法可以使它工作而无需创建一个我仅用于此目的的新接口?
Does that mean I have to create an interface, @Autowired it and let PermissionCheck
implement it? 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)
不会自动加载您的配置/beans/属性,除非附带专门的注释,例如 @ContextConfiguration
和 @TestPropertySource
.
@RunWith(SpringRunner.class)
does not automatically load your configurations/beans/properties unless accompanied with annotations that specifically do that, such as @ContextConfiguration
and @TestPropertySource
.
如果您的应用程序是Spring Boot应用程序,并且您希望加载整个上下文以及所有属性,则只需将 @SpringBootTest
批注添加到测试类中即可.
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.
参考文献:
这篇关于为什么@Autowired引发UnsatisfiedDependencyException,即使该类未实现任何接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!