![](/img/trans.png)
[英]How to inject mocks into a class that has 1 constructor with parameters?
[英]How to inject mocks with Springboot?
我想在我的 Springboot 應用程序中注入一個模擬。 我收到此錯誤:
Error creating bean with name 'ca.company.TestA': Unsatisfied dependency expressed through field 'a'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ca.company.hello.A' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我被卡住了,不明白如何處理。 我A
定義為自動裝配。 有什么問題?
這是我的測試文件:
@RunWith(SpringJUnit4ClassRunner.class)
public class TestA {
@Autowired
private A a;
private B Bmock;
@Before
public void before() {
Bmock = Mockito.mock(B.class);
ReflectionTestUtils.setField(a, "b", Bmock);
}
@Test
public void testSpeak() {
when(Bmock.writeToScreen()).thenReturn("Everything will be alright");
assert(true);
}
}
這是配置文件:
@Configuration
public class Config {
@Bean
public B b() {
return new B();
}
// The error persists whether I define this bean or not
@Bean
public A a() {
return new A();
}
}
這是有問題的 class :
@Component
public class A {
@Autowired
private B b;
public void speak() {
System.out.println(b.writeToScreen());
}
}
最后是我的文件結構:
我在做什么錯,我不明白。
您的配置 class 不被 Spring 處理。 實現這一目標的最簡單方法是將@ContextConfiguration(classes = Config.class)
放入您的測試 class 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.