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 = /* Your dynamic mock here */
}
在服务中,@Autowired 字段是私有的:
@Component("notificationService")
class NotificationServiceImpl extends NotificationService {
@Autowired private var domainManager: DomainManager = _
@Autowired private var templateService: TemplateService = _
@Autowired private var notificationConfig: NotificationConfig = _