我想将一个Mockito模拟对象注入一个Spring(3+)bean中,以便使用JUnit进行单元测试.我的bean依赖项目前通过@Autowired在私有成员字段上使用注释来注入.
我考虑过使用ReflectionTestUtils.setField但我希望注入的bean实例实际上是一个代理,因此不会声明目标类的私有成员字段.我不希望为依赖创建一个公共setter,因为我将修改我的界面纯粹是为了测试的目的.
我遵循了Spring社区给出的一些建议,但是没有创建模拟并且自动连线失败:
<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.package.Dao" />
</bean>
Run Code Online (Sandbox Code Playgroud)
我目前遇到的错误如下:
...
Caused by: org...NoSuchBeanDefinitionException:
No matching bean of type [com.package.Dao] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {
@org...Autowired(required=true),
@org...Qualifier(value=dao)
}
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)
Run Code Online (Sandbox Code Playgroud)
如果我将constructor-arg值设置为无效,则在启动应用程序上下文时不会发生错误.
我想使用spring-test配置内部类(@Configuration)配置组件测试.经过测试的组件有一些我想模拟测试的服务.这些服务是类(没有使用接口)并且@Autowired在其中具有spring注释().Mockito可以很容易地模仿它们,但是,我发现无法禁用弹簧自动装配.
我可以轻松重现的示例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SomeTest.Beans.class)
public class SomeTest {
// configured in component-config.xml, using ThirdPartyService
@Autowired
private TestedBean entryPoint;
@Test
public void test() {
}
@Configuration
@ImportResource("/spring/component-config.xml")
static class Beans {
@Bean
ThirdPartyService createThirdPartyService() {
return mock(ThirdPartyService.class);
}
}
}
public class ThirdPartyService {
@Autowired
Foo bar;
}
public class TestedBean {
@Autowired
private ThirdPartyService service;
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,"TestBean"表示要模拟的服务.我不希望春天注入"酒吧"!@Bean(autowire = NO)没有帮助(事实上,这是默认值).(请保存我从"使用界面!"评论 - 模拟服务可以是第三方,我无法做任何事情.)
UPDATE
Springockito部分解决了这个问题,只要你没有其他任何东西可以配置(所以你不能使用Springockito的配置类 - 它不支持它),但只使用模拟.还在寻找纯弹簧解决方案,如果有的话...
我有一个非常简单的单元测试:
@RunWith(MockitoJUnitRunner.class)
public class RestControllerTest {
protected MockMvc mockMvc;
@Autowired
WebApplicationContext wac;
@InjectMocks
protected RestController restController;
@Mock
protected UserService mockUserService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的测试中,我一直在弄清楚如何自动装配 WebApplicationContext。请有人指导我如何做到这一点。
PS 我正在使用 MockitoJUnitRunner 我不确定这是否有所作为。但是我是 Spring 和 Mockito 的新手,所以对这两种技术都不太了解。
junit ×3
mockito ×3
java ×2
spring ×2
annotations ×1
spring-mvc ×1
spring-test ×1
unit-testing ×1