seanhenry / SwiftMockGeneratorForXcode

An Xcode extension (plugin) to generate Swift test doubles automatically.
MIT License
748 stars 47 forks source link

Optional in stubbed properties #23

Closed fmirault closed 5 years ago

fmirault commented 5 years ago

Hi! I just used the mock generator for the first time, and I noticed that the stubbed properties don't match the signature method.

For example, if a method has this signature func object(forKey defaultName: String) -> Any? , the associated stubbed property is var stubbedObjectResult: Any!. I'd like to have instead of this var stubbedObjectResult: Any?, but maybe there is a reason that I don't get to not be able to have correct stubbed object ?

seanhenry commented 5 years ago

Hi @fmirault

Thanks for raising this issue.

I can see why you would want the type to match the return type in the method but this was my reasoning for the decision:

If the type of the stub property exactly matches the return type of the method then it won't always compile. Example when method returns guaranteed value:

...
var stubbedObjectResult: Any // won't compile
func object(forKey defaultName: String) -> Any {
  ...
  return stubbedObjectResult
}

The two ways to fix that would be to either:

var stubbedObjectResult: Any!

or:

return stubbedObjectResult!

The first approach works for all return types and the second option makes the mock a little more complex.

So I opted to keep things simpler, but also more flexible. For example, if you were to change the signature of:

func object(forKey defaultName: String) -> Any?

to:

func object(forKey defaultName: String) -> Any

then the mock wouldn't have to be regenerated.

fmirault commented 5 years ago

Hi @seanhenry

Thank you for your answer, now I better understand your choice :) It's not a huge problem, because my use case is that I want to test some methods with nil values, so I just have to change some generated code after using the generator, not the best practice because every time I use the generator I loose my changes, but in every case I save time thanks to your tool. Thank you very much !

seanhenry commented 5 years ago

No problem. I'm glad you like it :)

Do you mean you need your mock method to return nil? If so, you don't need to change the generated mock because it will return nil by default because the IUO will be converted to an optional.

Example:

class MyMock: MyType {
  ...
  var stubbedObjectResult: Any!
  func object(forKey defaultName: String) -> Any? {
    ...
    return stubbedObjectResult
  }
}

let mock = MyMock()
mock.object(forKey: "anyKey") == nil // true
fmirault commented 5 years ago

Oh you're right! I thought that I will have a crash (I don't really know why...) but it's working, so I don't have to change anything in the generated code, thank you ! 👍

seanhenry commented 5 years ago

👍