Search code examples
scalatestingasserttriple-equals

How to perform triple equals as negation


I am learning scala, and want to write my tests with ===. However, I am curious if there is a way to do something like this:

assert(1 !=== 2)

I have tried the above, !==, and !(===)

Is there any way to get the descriptiveness of === and use negation?


Solution

  • ScalaTest doesn't have a !== method (it's actually in the source code and is commented out). You could implement your own analogue, like:

    // Somewhere in the codebase
    class ExtendedEqualizer(left: Any) {
      def !==(right: Any) = {
        if (left != right) None
        else Some("%s equaled to %s".format(left, right))
      }
    }
    
    object TestUtil {
      implicit def convertToExtendedEqualizer(left: Any) = new ExtendedEqualizer(left)
    }
    
    // In your test class
    import TestUtil.convertToExtendedEqualizer
    

    Then it becomes as simple to use as ===:

    assert(3 !== 2+2)
    

    Note that this is a simplified version of === that doesn't do deep array comparisons and doesn't generate a nice diff like ScalaTest does.