Kolos65 / Mockable

A Swift macro driven auto-mocking library.
MIT License
233 stars 18 forks source link

Use MockService in SwiftUI Previews #26

Closed mihaicris-adoreme closed 6 months ago

mihaicris-adoreme commented 6 months ago

I guess this is not possible since the helpers are in MockableTest product not in Mockable product. But previews are located in the target not in the test target. Therefore even if we apply @Mockable macro to the Service, we cant use the helpers like given...willReturn... in Previews, correct?

Kolos65 commented 6 months ago

You can currently use it by accessing given() directly on the MockService:

@Mockable
protocol Service {
    func foo() -> String
}

func foo() {
    MockService().given()
        .foo().willReturn("hello")
}

If you do this in the latest version, you will get a deprecated warning I put there to indicate the intended use of the library (which is through the helpers).

The reason I needed a different target for the helpers is actually only the verify block, that uses XCTest framework's assertion to verify the number of calls to functions. (XCTest can only be linked to test targets so I could not depend on it in my main target).

As the main focus of Mockable was providing utils for writing unit tests (which are always written in test targets) I did not consider keeping given() and when() in the main target of the package. We could however keep them in the Mockable target and only encapsulate verify() in the MockableTest target.

Can you describe your use-case of using Mockable for previews a bit more in detail?

mihaicris-adoreme commented 6 months ago

Sure, I would like to mock the services response in SwiftUI previews , such that the previews would run faster and isolated from the external dependencies.

But I made this attached example, and given() is available in the Target (with deprecation warning), but willReturn is not. I understand Mockable was made for testing, but, somehow, Swift UI previews are also testing (UI testing) and would be great to be able to mock the responses also in the target. Sure, verify() is not needed for asserts since the asserting part is the UI rendering itself.

ExampleMockable.zip

Kolos65 commented 6 months ago

@mihaicris-adoreme your points are valid, I already prepared a pull request that will move given() and when() to the main Mockable target. Will let you know when I released a new version with the changes.

Thanks for the issue 🙏

Kolos65 commented 6 months ago

@mihaicris-adoreme given() and when() was moved to the Mockable target in 0.0.4

mihaicris-adoreme commented 6 months ago

Thank's a lot! Works great. 🙏