![](/img/trans.png)
[英]Why does this class compile even though it does not properly implement its interface?
[英]Why @Autowired raises UnsatisfiedDependencyException, even the class does not implement any interface?
这是我要测试的 class
@Component
public class PermissionCheck {
@Autowired
private MyEntityRepository myEntityRepository;
public boolean hasPermission(int myEntityID) {
MyEntity myEntity = myEntityRepository.findById(myEntityId);
return myEntity != null;
}
}
这里是测试 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));
}
}
当我运行这个测试时,我得到了
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 问题(例如这个问题)中,我看到当目标 class 实现接口时会发生这种情况。 但是从代码中我们可以看出, PermissionCheck
没有实现任何接口,那为什么还是抛出异常呢?
这是否意味着我必须创建一个接口,@Autowired 并让PermissionCheck
实现它? 这对我来说似乎是多余的,因为我不明白为什么我需要这样的接口。 有没有办法让它工作而无需创建我将仅用于此目的的新界面?
@RunWith(SpringRunner.class)
不会自动加载您的配置/beans/properties,除非附带专门执行此操作的注释,例如@ContextConfiguration
和@TestPropertySource
。
如果您的应用程序是 Spring 引导应用程序并且您想要加载整个上下文以及所有属性,您可以简单地将@SpringBootTest
注释添加到您的测试 class 中。
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.