Hi Ayose,
You can use a manifest to get rid of the classOf, and you can use
BeMatcher instead of a Matcher to be able to put it after "be".
import org.scalatest._
import matchers.ShouldMatchers._
import matchers.Matcher
import matchers.BeMatcher
import matchers.MatchResult
def beOfType[T: Manifest] = Matcher { obj: Any =>
val cls = manifest[T].erasure
MatchResult(
obj.getClass == cls,
obj.toString + " was not an instance of " + cls.toString,
obj.toString + " was an instance of " + cls.toString
)
}
def ofType[T: Manifest] = BeMatcher { obj: Any =>
val cls = manifest[T].erasure
MatchResult(
obj.getClass == cls,
obj.toString + " was not an instance of " + cls.toString,
obj.toString + " was an instance of " + cls.toString
)
}
"hi" should beOfType[String]
"hi" should not (beOfType[String])
"hi" should be (ofType[String])
"hi" should not be ofType[String]
A matcher for this use case, by the way, will be included in our
matchers enhancements post-2.0.
Bill
On Sun, Aug 26, 2012 at 8:56 AM, Ayose Cazorla <
ayo...@gmail.com> wrote:
>
> Hi people,
>
> I wanted to check the type of an object in a set. After searching for a
> matcher in the current Scalatest documentation, I decided to write my own
> matcher. This is
>
> def beOfType(cls: Class[_]) = Matcher { obj: Any =>
> MatchResult(
> obj.getClass == cls,
> obj.toString + " was not an instance of " + cls.toString,
> obj.toString + " was an instance of " + cls.toString
> )
> }
>
> (Full source at
https://gist.github.com/3481251)
>
> Previously I was using
>
> result.rejections.head.isInstanceOf[AuthenticationRequiredRejection]
> must be (true)
>
> But, with this, when it fails I don't see what is the actual object, just
> the message «false was not true», which is not very useful.
>
> Now, I have
>
> result.rejections.head must
> beOfType(classOf[AuthenticationRequiredRejection])
>
> My question is: is this a good way to solve the problem? Is there any better
> way?
>
>
> --
> You received this message because you are subscribed to the Google
> Groups "scalatest-users" group.
> To post to this group, send email to
scalate...@googlegroups.com
> To unsubscribe from this group, send email to
>
scalatest-use...@googlegroups.com
> For more options, visit this group at
>
http://groups.google.com/group/scalatest-users?hl=en
> ScalaTest itself, and documentation, is available here:
>
http://www.artima.com/scalatest
--
Bill Venners
Artima, Inc.
http://www.artima.com