![](/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.