Cuckoo icon indicating copy to clipboard operation
Cuckoo copied to clipboard

Optional @objc property

Open paiv opened this issue 5 years ago • 2 comments

Trying to mock this protocol:

@objc protocol Example {
    @objc optional var ignore: String { get }
}

Generates mock class with compilation error:

     var ignore: String {
        get {
            return cuckoo_manager.getter("ignore",
                superclassCall:
                    
                    Cuckoo.MockManager.crashOnProtocolSuperclassCall()
                    ,
                defaultCall: __defaultImplStub!.ignore)
//                                              ^
// Value of optional type 'String?' must be unwrapped to a value of type 'String'
        }
        
    }

paiv avatar Jan 24 '20 14:01 paiv

@MatyasKriz Hi, can I take this issue and work on it?

jungwonJung avatar Sep 21 '25 20:09 jungwonJung

Hi @jungwonJung, absolutely, go for it. 🙂

I think I tried my hand but had some problems with generated mocks compilation. The type Attribute is the type to contain the information, it already has the objc case.

MatyasKriz avatar Sep 23 '25 21:09 MatyasKriz

Good day, @paiv, I see that we are dealing with legacy code, so I would recommend avoiding utilising Cuckoo. If I am correct, did you try to start by labelling the string as null?

as I believe this would solve some issues also added comments to explain further

import Foundation

@objc protocol Example {
 @objc optional var ignore: String { get }
}
class ExampleImpl: NSObject, Example {
 var ignore: String {
     return "Hello from real implementation"
 }
}
class MockExample: NSObject, Example {
 // Configurable storage for the optional property
 // Use this to simulate returning a value from the optional requirement
 var ignoreStub: String?

 // Because the protocol's property is optional, we can choose to implement it or not.
 // Here we provide an implementation that returns the stubbed value or an empty string by default.
 var ignore: String {
     return ignoreStub ?? ""
 }
}

Tsebo200 avatar Dec 14 '25 01:12 Tsebo200