I have a static method in class
class A {
static func myStaticMethod() -> B {
return B()
}
}
class B {
func getTitle() -> String {
// some functionality here
}
}
In my class method that i want to test i use it like:
func someBoolFunc() -> Bool {
var b = A.myStaticMethod()
if (b.getTitle() = “hello”) {
return true
}
return false
}
How to write mock class for this... I 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 it is only in theory :(
Note that static methods cannot be mocked easily. As an example, if you have two classes named A and B and class A uses a static member of class B, you wouldn't be able to unit test class A in isolation.
Mocking Static Methods Free tools like Moq can only mock interfaces or virtual/abstract methods on classes with a public default constructor. If you need to truly mock static methods, you need to use a commercial tool like Microsoft Fakes (part of Visual Studio Enterprise) or Typemock Isolator.
Mocking Static Classes, Methods, and Properties Overview The difference between the two classes is that a static class cannot be instantiated. The new operator cannot create a variable of the class type. Because there is no instance variable, the class name itself should be used to access the members of a static class.
In automated tests, it is creating an object that conforms to the same behavior as the real object it is mocking. Many times the object you want to test has a dependency on an object that you have no control over. There are several ways to create iOS unit testing mock objects. One way is to subclass it.
Maybe this way?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With