【发布时间】:2018-06-15 20:26:51
【问题描述】:
这是我的测试代码
package com.tasks;
@ContextConfiguration(classes = ITest.class)
@ActiveProfiles(profiles = "test")
@RunWith(SpringJUnit4ClassRunner.class)
public class ITest {
@Inject
IAccessor iAccessor1;
@Test
public void testRun() {
}
@Configuration
@Profile("test")
@ComponentScan(basePackageClasses{com.tasks.ITest.class})
public static class ITestConfiguration{
@Bean
@Primary
public IAccessor iDataAccessor(){
IAccessor iAccessor = mock(IAccessor.class);
return iAccessor;
}
}
}
我尝试了@Autowired 而不是 Inject,但得到了同样的错误。
在我的测试课中,我有
@Component
public class ISync {
@Inject
private IAccessor iAccessor;
public int someMethod(){
iAccessor.someOtherMethod(); //want to mock out
}
}
所以我想注入一个模拟值。但是我得到一个依赖错误
org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 符合条件的 bean 类型 'com.database.iAccessor1' 可用: 预计至少有 1 个 bean 有资格作为 autowire 候选者。 依赖注解:{@javax.inject.Inject()}
它通常对我有用,但我不知道在这种特殊情况下这里有什么问题。 我想知道我的解决方案有什么问题。
我已经尝试过: Spring JUnit: How to Mock autowired component in autowired component 1) 接受的答案是使用 testContext.xml 我不使用任何 xml。 2) 我使用了@MockBean,但开始出现其他错误。
java.lang.NoSuchMethodError: org.mockito.Mockito.mockingDetails(Ljava/lang/Object;)Lorg/mockito/MockingDetails;
为了纠正它,我将 mockito-all 1.9.0 的版本升级到了 1.9.5(虽然我不知道它为什么试图找到它)。
java.lang.NoSuchMethodError: org.mockito.internal.util.MockUtil.getMockSettings(Ljava/lang/Object;)Lorg/mockito/mock/MockCreationSettings;
我通过将版本升级到 1.0.19 来让它工作。但是被测类中的值仍然为空。所以这对我不起作用。
我想知道我原来的解决方案有什么问题?
【问题讨论】:
-
也只看左边的“相关”问题,这不是一个新问题。
-
为什么要注入“模拟”值?为什么不直接通过 @Mock 或 mock(...) 使用模拟?
-
@tkruse 我想知道我的解决方案中的问题。当前的解决方案还要求我升级版本。如果我想保持在同一个版本上,我需要我的解决方案才能工作。
-
@SeanCarroll Mock 创建了一个 mock,但不会将其注入到 autowired 属性中,该属性在调用该类的函数时将为 null。
标签: spring unit-testing junit dependency-injection spring-test