Fast unit tests

I have a static method in a class

class A {
    static func myStaticMethod() -> B {
        return B()
    }
}

class B {
    func getTitle() -> String {
        // some functionality here
    }
}

      

In my method of the class that I want to check, I use it like:

func someBoolFunc() -> Bool {
    var b = A.myStaticMethod()
    if (b.getTitle() = "hello") {
         return true
    }
    return false
}

      

How do I write a mock class for this ... I've tried:

class MockA: A {
    var myTitle:String
    // this seems incorrect, because i didn't override static function
    func myStaticMethod() -> MockB {
        var b = MockB()
        b.title = myTitle
        return b
    }
}

class MockB: B {
    var myTitle:String    

    func getTitle() -> String {

        return myTitle
    }
}

      

And in tests, I wanted to use something like:

func testExample() {
    A = MockA
    MockA.title = "My title"
    // And now this func should use my MockA instead of A
    someBoolFunc()
}

      

But, of course, this is only in theory :(

+3


source to share


1 answer


Maybe so?



protocol AProto {
  static func myStaticMethod() -> BProto
}

class A: AProto {
  static func myStaticMethod() -> BProto {
    return B()
  }
}

class MockA: AProto {
  static func myStaticMethod() -> BProto {
    return MockB()
  }
}

protocol BProto {
  func getTitle() -> String
}

class B: BProto {
  func getTitle() -> String {
    return "hello"
  }
}

class MockB: BProto {
  func getTitle() -> String {
    return "bye bye"
  }
}

func someBoolFunc(_ aProto: AProto.Type = A.self) -> Bool {
  var b = aProto.myStaticMethod()
  if (b.getTitle() == "hello") {
    return true
  }
  return false
}

print(someBoolFunc())
print(someBoolFunc(MockA.self))

      

+3


source







All Articles