Mockito matchers, scala value class and NullPointerException

后端 未结 6 1930
遇见更好的自我
遇见更好的自我 2020-12-15 04:16

I\'m using mockito with scalatest. I have following problem when using matcher with value class.

import org.scalat         


        
相关标签:
6条回答
  • 2020-12-15 04:56

    This works for all kinds of extends AnyVal value classes and doesn't need special matchers either:

        given(mockedClass.someMethods(FirstId(anyString), SecondId(org.mockito.Matchers.eq(secondId.value)))).willReturn(3)
    
    0 讨论(0)
  • 2020-12-15 05:03

    The newest version of mockito-scala (0.0.9) supports this out of the box, you can do something like

    when(myObj.myMethod(anyVal[MyValueClass]) thenReturn "something"
    
    myObj.myMethod(MyValueClass(456)) shouldBe "something"
    
    verify(myObj).myMethod(eqToVal[MyValueClass](456))
    

    Disclaimer: I'm a developer of that library

    0 讨论(0)
  • 2020-12-15 05:04

    The proper solution is:

    case class StringValue(val text: String) extends AnyVal
    case class LongValue(val value: Long) extends AnyVal
    
    val eqFirst: StringValue = StringValue(org.mockito.Matchers.eq("first"))
    val anySecond: StringValue = StringValue(org.mockito.Matchers.any[String])
    
    val eqFirst: LongValue = LongValue(org.mockito.Matchers.eq(1L))
    val anySecond: LongValue = LongValue(org.mockito.Matchers.any[Long])
    
    0 讨论(0)
  • 2020-12-15 05:06

    If you have shapeless in your dependencies you could consider my little helper method: https://gist.github.com/Fristi/bbc9d0e04557278f8d19976188a0b733

    Instead of writing

    UserId(is(context.userId.value))

    You can write

    isAnyVal(context.userId)

    Which is a bit more convenient :-)

    0 讨论(0)
  • 2020-12-15 05:10

    I found solution:

    val anyFirstId: FirstId = any[String].asInstanceOf[FirstId]
    val eqSecondId: SecondId = org.mockito.Matchers.eq[String](secondId.value).asInstanceOf[SecondId]
    given(mockedClass.someMethods(anyFirstId, eqSecondId)).willReturn(3)
    
    0 讨论(0)
  • 2020-12-15 05:21

    My class also extended AnyVal

    case class ApplicationKey(value: String) extends AnyVal {
      override def toString: String = value
    }
    

    and this worked for me:

       when(waterfallLogicEventWriter.writeAuctionEvents(            
         Eq(waterfallRequest.auctionId), Eq(waterfallRequest.ip),
         ApplicationKey(any[String]),                                
         any()).thenReturn(waterfallEvents) 
    
    0 讨论(0)
提交回复
热议问题