【发布时间】:2023-03-11 20:10:02
【问题描述】:
我有一些具有混合特征的组件,其中包含系统逻辑(缓存、服务等)。并且需要在测试中模拟这个逻辑。很简单……
但我还需要测试具有相同缓存的组件包,并且我无法共享一些全局缓存。所以,我的解决方案是:
在代码中:
trait Component
class MyComponent1 extends Component with Cache with Services { ... }
class MyComponent2 extends Component with Cache with Services { ... }
trait Cache {
private val _cache = ...
def query(...) = ...
}
在测试 API 中:
trait CacheMock extends Cache {
private[package] var _cache = null //to be injected
override def query(...) = _cache.get(...)
}
case class Config(cacheMock: Cache)
trait TestAPI {
val componentCreator: => List[Component]
def test(config: Config) = {
val instances = componentCreator
instances foreach {
case mocked: CacheMock => mocked._cache = config.cacheMock
case _ =>
}
instances
}
}
在测试中:
class Test extends TestAPI {
def componentCreator = List(new MyComponent1 with CacheMock, new MyComponent2 with CacheMock)
test(Config(mock1))
test(Config(mock2))
}
另一种解决方案是在componentCreator中使用参数化工厂:Cache => List[Component],但它有点难看。
那么有没有更好的解决方案,它也可以提供一个简单的 DSL(没有样板),但没有 var 分配?或者可以解决同样问题的框架?
【问题讨论】:
标签: scala integration-testing mixins