如何自动连接服务,进而自动连接Junit中的另一项服务



TestSomething.class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "application-context-junit" })
public class TestSomething {
@Autowired
ISomeService someService;
...// more code 
}

SomeServiceImpl.class:

@Service("someService")
public class SomeServiceImpl implements ISomeService{
@Autowired
ISomeAnotherService someAnotherService;
..//more code
}

application-context-junit.xml:

<context:component-scan base-package="com.basepackage.*" />

所以,我的问题是如果我在application-context-junit.xml中提供组件扫描来处理所有Autowires,这就足够了吗?还是应该在xml中添加以下内容

<context:component-scan base-package="com.basepackage.*" />
<bean id="someService" class=""com.basepackage.SomeServiceImpl"" />
<bean id="someAnotherService" class=""com.basepackage.SomeAnotherServiceImpl"" />

每次使用字段注入时,单元测试都会失败!

不要使用锉刀注射,因为这不是一个好的做法。此外,当Spring必须为每个测试注入类时,它会减慢测试速度。

正如您在本文中所读到的,最好使用构造函数或setter注入。

这种类型的注入可以很容易地模拟被测试组件使用的所有组件,如下所示:

import org.junit.Before;
import org.mockito.Mockito;
public class MyBeanTest {
private MyBean target = new MyBean();
private AnotherBean anotherBean = Mockito.mock(AnotherBean.class);
@Before
public void setUp() {
myBean.setAnotherBean(anotherBean);
}
//Tests...
}

最新更新