测试一些内存消耗大的代码

Testing some heavy memory consumption code

我有一些缓存-class,它聚合了一些 heavy 对象以在生产中进行优化。我需要测试使用缓存但与缓存无关的逻辑的代码。如何避免使用缓存? 运行 即时获取对象,不使用缓存。我想过反思,但它迫使我痛苦。是设计问题还是我尝试做错了什么?

case class SomeObject()

class FooService(private val cacheMap: collection.mutable.Map[String, SomeObject]) {

  /// some cache logic with put objects to cache

  def put(key: String, value: SomeObject): collection.mutable.Map[String, SomeObject] = cacheMap += key -> value

  def get(key: String): Option[SomeObject] = cacheMap.get(key)

  private def loadFromFile(file: String): SomeObject = ???

  def loadObject(key: String): SomeObject = {
      // ... some logic from loading 
    cacheMap.getOrElseUpdate(key, loadFromFile("some_path"))
  }
}


class Bar {

  val fooCache = new FooService(collection.mutable.Map.empty[String, SomeObject])

  def methodForTest(args: List[String]): SomeObject = {
    // do some logic ...
    val someObject = fooCache.loadObject("someKey") // here I can't create filePath for loading directly from file
    // fooCache updates, but I don't want it
    someObject
  }
}

你需要一点控制反转:

1) 将 FooService 设为 trait,所有方法均未实现

2) 将已实现方法的 FooService 重命名为 FooServiceImpl,使其成为 extend FooService

此时您应该考虑哪个方法将成为接口 FooService 的一部分,哪个将隐藏在 FooServiceImpl 中。 很可能 FooService 不需要 loadObjectget

3) 使 fooCache 成为 Bar 中的构造函数参数:

class Bar(fooCache: FooService)

4) 当 运行 测试通过时 FooService 的更简单实现:

assert(new Bar(new DummyService)).methodForTest(Nil) == "Expected")