Spring的ContextConfiguration可以帮助您实现这一点。
例如,在下面的测试上下文中,“Local”类是模拟类。NotificationService
是我要测试的类。
我正在使用组件扫描将模拟类引入上下文,但您也可以轻松地使用<bean>
声明。请注意使用use-default-filters="false"。
<context:component-scan base-package="com.foo.config" use-default-filters="false">
<context:include-filter type="assignable"
expression="com.foo.LocalNotificationConfig"/>
</context:component-scan>
<context:component-scan base-package="com.foo.services.notification"
use-default-filters="false">
<context:include-filter type="assignable"
expression="com.foo.services.notification.DelegatingTemplateService"/>
<context:include-filter type="assignable"
expression="com.foo.services.notification.NotificationService"/>
</context:component-scan>
<context:component-scan base-package="com.foo.domain"/>
DelegatingTemplateService是一个带有@Delegate注解的Groovy类。
class DelegatingTemplateService {
@Delegate
TemplateService delegate
}
在测试类中,我使用测试上下文并注入服务进行测试。在设置中,我设置了DelegatingTemplateService的委托:
@RunWith(classOf[SpringJUnit4ClassRunner])
@ContextConfiguration(Array("/spring-test-context.xml"))
class TestNotificationService extends JUnitSuite {
@Autowired var notificationService: NotificationService = _
@Autowired var templateService: DelegatingTemplateService = _
@Before
def setUp {
templateService.delegate =
}
在服务中,@Autowired字段是私有的:
@Component("notificationService")
class NotificationServiceImpl extends NotificationService {
@Autowired private var domainManager: DomainManager = _
@Autowired private var templateService: TemplateService = _
@Autowired private var notificationConfig: NotificationConfig = _
new
关键字创建了MyService类的实例。 - matt b