【问题标题】:Stackable traits for mocking shared state用于模拟共享状态的可堆叠特征
【发布时间】: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


    【解决方案1】:

    不像你的代码那样编译,但它应该解释我的想法:

    class TestMyComponent1(protected _cache: Cache) extends MyComponent1 with CacheMock
    class TestMyComponent2(protected _cache: Cache) extends MyComponent2 with CacheMock
    
    trait CacheMock extends Cache {
       protected val _cache: Cache
       override def query(...) = _cache.get(...)
    }
    
    class Test extends TestAPI {
      def componentCreator = List(new TestMyComponent1(mock1), new TestMyComponent2(mock2))
    }
    

    【讨论】:

    • 这是“参数化工厂”,就像我说的那样有点难看 - 因为你必须 """blabla => List(Component1(blabla), Component2(blabla))""", " ""TestMyComponent1(protected _blabla: Cache)""" 等等......所以我只是在寻找更简单但也更流畅的东西
    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多