BeAnInstanceOf.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import Foundation
  2. /// A Nimble matcher that succeeds when the actual value is an _exact_ instance of the given class.
  3. public func beAnInstanceOf<T>(_ expectedType: T.Type) -> Predicate<Any> {
  4. let errorMessage = "be an instance of \(String(describing: expectedType))"
  5. return Predicate.define { actualExpression in
  6. let instance = try actualExpression.evaluate()
  7. guard let validInstance = instance else {
  8. return PredicateResult(
  9. status: .doesNotMatch,
  10. message: .expectedActualValueTo(errorMessage)
  11. )
  12. }
  13. let actualString = "<\(String(describing: type(of: validInstance))) instance>"
  14. return PredicateResult(
  15. status: PredicateStatus(bool: type(of: validInstance) == expectedType),
  16. message: .expectedCustomValueTo(errorMessage, actualString)
  17. )
  18. }
  19. }
  20. /// A Nimble matcher that succeeds when the actual value is an instance of the given class.
  21. /// @see beAKindOf if you want to match against subclasses
  22. public func beAnInstanceOf(_ expectedClass: AnyClass) -> Predicate<NSObject> {
  23. let errorMessage = "be an instance of \(String(describing: expectedClass))"
  24. return Predicate.define { actualExpression in
  25. let instance = try actualExpression.evaluate()
  26. let actualString: String
  27. if let validInstance = instance {
  28. actualString = "<\(String(describing: type(of: validInstance))) instance>"
  29. } else {
  30. actualString = "<nil>"
  31. }
  32. #if canImport(Darwin)
  33. let matches = instance != nil && instance!.isMember(of: expectedClass)
  34. #else
  35. let matches = instance != nil && type(of: instance!) == expectedClass
  36. #endif
  37. return PredicateResult(
  38. status: PredicateStatus(bool: matches),
  39. message: .expectedCustomValueTo(errorMessage, actualString)
  40. )
  41. }
  42. }
  43. #if canImport(Darwin)
  44. extension NMBObjCMatcher {
  45. @objc public class func beAnInstanceOfMatcher(_ expected: AnyClass) -> NMBMatcher {
  46. return NMBPredicate { actualExpression in
  47. return try beAnInstanceOf(expected).satisfies(actualExpression).toObjectiveC()
  48. }
  49. }
  50. }
  51. #endif