2

Is there a fluent matching API that works for Swift code? The leading Objective-C matcher candidates seem to be OCHamcrest and Expecta, both of which rely on complex macros that (as per the docs) aren't available to Swift code, e.g.

#define HC_assertThat(actual, matcher)  \
    HC_assertThatWithLocation(self, actual, matcher, __FILE__, __LINE__)

(OCHamcrest)

#define EXP_expect(actual) _EXP_expect(self, __LINE__, __FILE__, ^id{ return EXPObjectify((actual)); })

(Expecta)

Is there another alternative that does work with Swift, or some way to wrap one or the other of these so they can be used with Swift?


ETA: For future readers -- I looked at SwiftHamcrest (per Jon Reid's answer) but for the time being I've settled on Quick/Nimble.

Community
  • 1
  • 1
David Moles
  • 48,006
  • 27
  • 136
  • 235

2 Answers2

2

Complex preprocessor macros aren't translated to their Swift alternatives. Apple has a Blog discussing Swift, in which they described on how they made the assert function.

The first macro is easy to make into a Swift function

#define HC_assertThat(actual, matcher)  \
    HC_assertThatWithLocation(self, actual, matcher, __FILE__, __LINE__)

In Swift:

func HC_assertThat(caller: AnyObject, actual: String, matcher: String, file: String = __FILE__, line: UWord = __LINE__) {
    HC_assertThatWithLocation(caller, actual, matcher, file.fileSystemRepresentation, Int32(line))
}

#define EXP_expect(actual) _EXP_expect(self, __LINE__, __FILE__, ^id{ return EXPObjectify((actual)); })

In Swift:

func EXP_expect(caller: AnyObject, actual: String, line: UWord = __LINE__, file: String = __FILE__) {
    _EXP_expect(caller, Int32(line), file.fileSystemRepresentation, ({
        return EXPObjectify(caller)
    })
}

Note that I am guessing on what you want passed to the preprocessor functions.

MaddTheSane
  • 2,981
  • 24
  • 27
  • For Expecta for some reason in swift _EXP_expect can be called but EXPObjectify and _EXPObjectify are not visible . I can see them declared in the objective-c header and I have imported this in to the bridging header but no luck. Any idea how to get it working? – Imran Dec 23 '14 at 09:37
1

https://github.com/nschum/SwiftHamcrest is a Swift-native implementation of Hamcrest

Jon Reid
  • 20,545
  • 2
  • 64
  • 95