org.scalatest.LoneElement.scala Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of scalatest_2.9.1 Show documentation
Show all versions of scalatest_2.9.1 Show documentation
ScalaTest is a free, open-source testing toolkit for Scala and Java
programmers.
The newest version!
package org.scalatest
import collection.GenTraversable
import matchers.ShouldMatchers.TraversableShouldWrapper
/**
* Trait that provides an implicit conversion that adds a loneElement method
* to GenTraversable, which will return the value of the lone element if the collection does
* indeed contain one and only one element, or throw TestFailedException if not.
*
*
* This construct allows you to express in one statement that a collection should contain one and only one element
* and that the element value should meet some expectation. Here's an example:
*
*
*
* set.loneElement should be > 9
*
*
*
* Or, using an assertion instead of a matcher expression:
*
*
*
* assert(set.loneElement > 9)
*
*/
trait LoneElement {
/**
* Wrapper class that adds a loneElement method to GenTraversable.
*
*
* Through the implicit conversion provided by trait LoneElement, this class allows you to make statements like:
*
*
*
* trav.loneElement should be > 9
*
*
* @param trav A GenTraversable to wrap in a LoneElementTraversableWrapper, which provides the loneElement method.
*/
final class LoneElementTraversableWrapper[T](trav: GenTraversable[T]) {
/**
* Returns the value contained in the wrapped GenTraversable, if it contains one and only one element, else throws TestFailedException with
* a detail message describing the problem.
*
*
* This method enables syntax such as the following:
*
*
*
* trav.loneElement should be > 9
* ^
*
*/
def loneElement: T = {
if (trav.size == 1)
trav.head
else
throw new exceptions.TestFailedException(
Some(FailureMessages(
"notLoneElement",
trav,
trav.size)),
None,
1
)
}
}
/**
* Implicit conversion that adds a loneElement method to GenTraversable.
*
* @param trav the GenTraversable on which to add the loneElement method
*/
implicit def convertToTraversableLoneElementWrapper[T](trav: GenTraversable[T]): LoneElementTraversableWrapper[T] = new LoneElementTraversableWrapper[T](trav)
}
/**
* Companion object that facilitates the importing of LoneElement members as
* an alternative to mixing it in. One use case is to import LoneElement's members so you can use
* loneElement in the Scala interpreter.
*/
object LoneElement extends LoneElement
© 2015 - 2025 Weber Informatics LLC | Privacy Policy