Scalatest should include




















In this way, the isAdmin method can be tested by mocking out the UserRepository reference and passing it into the service:. Since your controllers are just regular classes, you can easily unit test them using Play helpers.

If your controllers depends on another classes, using dependency injection will enable you to mock these dependencies. Per instance, given the following controller:. For this, the test Helpers. Next: Writing functional tests with ScalaTest. Found an error in this documentation? The source code for this page can be found here. After reading the documentation guidelines , please feel free to contribute a pull request. Have questions or advice to share? The " contain inOrderOnly " syntax lets you assert that the containing object contains only the specified objects, in order.

The " contain inOrder " syntax lets you assert that the containing object contains only the specified objects in order, like inOrderOnly , but allows other objects to appear in the left-hand aggregation as well: contain more than one of each:. Lastly, the " contain theSameElementsInOrderAs " syntax lets you assert that two aggregations contain the same exact elements in the same iteration order:. TreeSet 3 , 2 , 1. The previous assertion succeeds because the iteration order of a TreeSet is the natural ordering of its elements, which in this case is 1, 2, 3.

An iterator obtained from the left-hand List will produce the same elements in the same order. You can also ask whether the elements of "sortable" objects such as Array s, Java List s, and GenSeq s are in sorted order, like this:.

List 1 , 2 , 3 shouldBe sorted. Although it seems desirable to provide similar matcher syntax for Scala and Java iterators to that provided for sequences like Seq s, Array , and java. List , the ephemeral nature of iterators makes this problematic.

Some syntax such as should contain is relatively straightforward to support on iterators, but other syntax such as, for example, Inspector expressions on nested iterators is not.

Rather than allowing inconsistencies between sequences and iterators in the API, we chose to not support any such syntax directly on iterators:. Instead, you will need to convert your iterators to a sequence explicitly before using them in matcher expressions:.

We recommend you convert Scala or Java iterators to Stream s, as shown in the previous example, so that you can continue to reap any potential benefits provided by the laziness of the underlying iterator. You can use the Inspectors syntax with matchers as well as assertions. If you have a multi-dimensional collection, such as a list of lists, using Inspectors is your best option:.

For assertions on one-dimensional collections, however, matchers provides "inspector shorthands. The previous statement asserts that all elements of the xs list should be less than All of the inspectors have shorthands in matchers. Here is the full list:. Note: in the current 2. M6-SNAP release, the type of object used with inspector shorthands must be GenTraversable , but this will likely be widened to include Java collections, arrays, iterators, etc.

To assert both that a collection contains just one "lone" element as well as something else about that element, you can use the loneElement syntax. For example, if a Set[Int] should contain just one element, an Int less than or equal to 10, you could write:. You can invoke loneElement on any type T for which an implicit Collecting[E, T] is available, where E is the type returned by the loneElement invocation. You can use similar syntax on Java collections java.

Collection and maps java. For example, you can check whether a Java Collection or Map is empty , like this:. Even though Java's List type doesn't actually have a length or getLength method, you can nevertheless check the length of a Java List java.

List like this:. In addition, you can check whether a Java Collection contains a particular element, like this:. One difference to note between the syntax supported on Java and Scala collections is that in Java, Map is not a subtype of Collection , and does not actually define an element type. Entry , but a Map is not actually a collection of Entry.

To make Java Map s easier to work with, however, ScalaTest matchers allows you to treat a Java Map as a collection of Entry , and defines a convenience implementation of java. Entry in org. Here's how you use it:. You can also just check whether a Java Map contains a particular key, or value, like this:. You can also use all the syntax described above for Scala and Java collections on Array s and String s.

All uses of be other than those shown previously perform an equality comparison. They work the same as equal when it is used with default equality. This redundancy between be and equals exists in part because it enables syntax that sometimes sounds more natural. For example, instead of writing:. Hopefully you won't write that too much given null is error prone, and Option is usually a better, well, option.

Here are some other examples of be used for equality comparison:. As with equal used with default equality, using be on arrays results in deep being called on both arrays prior to calling equal.

As a result, the following expression would not throw a TestFailedException :. Because be is used in several ways in ScalaTest matcher syntax, just as it is used in many ways in English, one potential point of confusion in the event of a failure is determining whether be was being used as an equality comparison or in some other way, such as a property assertion.

To make it more obvious when be is being used for equality, the failure messages generated for those equality checks will include the word equal in them. For example, if this expression fails with a TestFailedException :.

The detail message in that TestFailedException will include the words "equal to" to signify be was in this case being used for equality comparison:. Some 2 was not equal to Some 1.

If you wish to check the opposite of some condition, you can simply insert not in the expression. Here are a few examples:. ScalaTest should. Matchers trait includes the following syntax for that purpose:. If you want to ensure that a snippet of code does not compile because of a type error as opposed to a syntax error , use:. Note that the shouldNot typeCheck syntax will only succeed if the given snippet of code does not compile because of a type error.

A syntax error will still result in a thrown TestFailedException. If you want to state that a snippet of code does compile, you can make that more obvious with:.

Although the previous three constructs are implemented with macros that determine at compile time whether the snippet of code represented by the string does or does not compile, errors are reported as test failures at runtime. For example, this and -expression would not compile, because the parentheses are missing:.

First, expressions with and and or do not short-circuit. The following contrived expression, for example, would print "hello, world! In other words, the entire and or or expression is always evaluated, so you'll see any side effects of the right-hand side even if evaluating only the left-hand side is enough to determine the ultimate result of the larger expression. Failure messages produced by these expressions will "short-circuit," however, mentioning only the left-hand side if that's enough to determine the result of the entire expression.

This "short-circuiting" behavior of failure messages is intended to make it easier and quicker for you to ascertain which part of the expression caused the failure.

The failure message for the previous expression, for example, would be:. Most likely this lack of short-circuiting would rarely be noticeable, because evaluating the right hand side will usually not involve a side effect. One situation where it might show up, however, is if you attempt to and a null check on a variable with an expression that uses the variable, like this:.

Here, the NullPointerException is the visible right-hand side effect. To get a TestFailedException , you would need to check each assertion separately:. If map is null in this case, the null check in the first expression will fail with a TestFailedException , and the second expression will never be executed.

If you really want the and part to be evaluated first, you'll need to put in parentheses, like this:. You can work with options using ScalaTest's equality, empty , defined , and contain syntax. For example, if you wish to check whether an option is None , you can write any of:. If you only wish to check that an option is defined, but don't care what it's value is, you can write:.

If you mix in or import the members of OptionValues , you can write one statement that indicates you believe an option should be defined and then say something else about its value. As mentioned previously, you can use also use ScalaTest's contain , contain oneOf , and contain noneOf syntax with options:. Using have , you can check properties of any type, where a property is an attribute of any object that can be retrieved either by a public field, method, or JavaBean-style get or is method, like this:.

This expression will use reflection to ensure the title , author , and pubYear properties of object book are equal to the specified values. For example, it will ensure that book has either a public Java field or method named title , or a public method named getTitle , that when invoked or accessed in the field case results in the string "Programming in Scala".

If all specified properties exist and have their expected values, respectively, execution will continue. If one or more of the properties either does not exist, or exists but results in an unexpected value, a TestFailedException will be thrown that explains the problem.

For the details on how a field or method is selected during this process, see the documentation for HavePropertyMatcherGenerator. When you use this syntax, you must place one or more property values in parentheses after have , separated by commas, where a property value is a symbol indicating the name of the property followed by the expected value in parentheses.

The only exceptions to this rule is the syntax for checking size and length shown previously, which does not require parentheses.

If you forget and put parentheses in, however, everything will still work as you'd expect. Thus instead of writing:. If a property has a value different from the specified expected value, a TestFailedError will be thrown with a detailed message that explains the problem. For example, if you assert the following on a book whose title is Moby Dick :. If you prefer to check properties in a type-safe manner, you can use a HavePropertyMatcher. These expressions would fail to compile if should is used on an inappropriate type, as determined by the type parameter of the HavePropertyMatcher being used.

For example, title in this example might be of type HavePropertyMatcher[org. If used with an appropriate type, such an expression will compile and at run time the property method or field will be accessed directly; i. See the documentation for HavePropertyMatcher for more information.

For example, you could write:. Prior to ScalaTest 2. In ScalaTest 2. ScalaTest's Inside trait allows you to make assertions after a pattern match. You can use inside to just ensure a pattern is matched, without making any further assertions, but a better alternative for that kind of assertion is matchPattern.

The matchPattern syntax allows you to express that you expect a value to match a particular pattern, no more and no less:. If none of the built-in matcher syntax or options shown so far for extending the syntax satisfies a particular need you have, you can create custom Matcher s that allow you to place your own syntax directly after should.

For example, although you can ensure that a java. File has a name that ends with a particular extension like this:. You might prefer to create a custom Matcher[java.

File] named endWithExtension , so you could write expressions like:. One good way to organize custom matchers is to place them inside one or more traits that you can then mix into the suites that need them. Note: the CustomMatchers companion object exists to make it easy to bring the matchers defined in this trait into scope via importing, instead of mixing in the trait.

The ability to import them is useful, for example, when you want to use the matchers defined in a trait in the Scala interpreter console. Because the class extends Matcher[java. File] , the compiler will only allow it be used to match against instances of java. A matcher must declare an apply method that takes the type decared in Matcher 's type parameter, in this case java.

The apply method will return a MatchResult whose matches field will indicate whether the match succeeded. The failureMessage field will provide a programmer-friendly error message indicating, in the event of a match failure, what caused the match to fail.

The FileEndsWithExtensionMatcher matcher in this example determines success by determining if the passed java. File ends with the desired extension.

It does this in the first argument passed to the MatchResult factory method:. In other words, if the file name has the expected extension, this matcher matches. The next argument to MatchResult 's factory method produces the failure message string:. Project: daml Author: digital-asset File: RecordSpec. Collections import com. ValueOuterClass import org. Field new Int64 1l , new Record.

Field new Int64 2l record. Field "label1", new Int64 1l , new Record. Field "label2", new Int64 2l record. ImmArray import com. ImmArraySeq import com. Optional import com. Modifier import org.

Boolean] bool. Bar" , DottedName. Project: daml Author: digital-asset File: ConfSpec. Paths import org. UUID import com. PayOut import org. CallablePayout val createCommand: P. CallablePayout import com.

CallablePayout val givenContractId: P. Twoples alice, DA. SimpleListExample import com. Create rpccmd. CreateAndExercise rpccmd. Project: daml Author: digital-asset File: PrimitiveSpec. GeneratorDrivenPropertyChecks import shapeless. List: collection. ContractId[B]]", "Cannot prove that.

TemplateId[B]]", "Cannot prove that. Update[B]]", "Cannot prove that. Show import scalaz. CallablePayout alice, t. TrialSubRec 10, , List 1, 2, 3 , t. TrialEmptyRec , t. Text, P. TrialSubRec 11, , List 10, 20, 30 , t. CallablePayout]] P. ContractId "abc" , P. ContractId "def" "show t. StringEscapeUtils import org. CallablePayout, Sth. ContractId "def" "t.

TRight P. Create import com. TraceContext import com. Encoder[TestVoid] Value. Project: daml Author: digital-asset File: TemplateSpec. Int64] c illTyped "cna. CNA]", "? Text, template: P. Int64, create: P. Int64, namedArguments: P. Int64, archive: P. MalformedTypesafeConfig import com. ConfigFactory import org. FutureOps import org. Project: daml Author: digital-asset File: UtilTest. IOException import java. BasicFileAttributes import java.

LFUtil scalaPackage, I. Template, QualifiedName assertFromString "foo. Identifier import com. Normal tmpl. Template fooRec, DefTemplate Map. Project: daml Author: digital-asset File: NamespaceSpec. GeneratorDrivenPropertyChecks import scalaz. Project: daml Author: digital-asset File: GraphSpec. QualifiedName import org. PartyState import org. ApiTypes import spray. QueryParser import sangria. DescriptionChange import sangria. Schema import scala. Project: daml Author: digital-asset File: FilterSpec.

PropertyCursor import com. ApiTypes import scalaz. EPOCH, template. ApiValue, typ: model. DamlLfType : Try[model. DamlLfType] C. Project: daml Author: digital-asset File: ModelSpec. Project: daml Author: digital-asset File: ConverterSpec. FileAlreadyExists import org. Project: daml Author: digital-asset File: PortSpec. ResourceOwner import org.

Project: daml Author: digital-asset File: EqualzSpec. FailedToLock lockedPort. Project: iotchain Author: iot-block File: testkit.

RlpCodec import jbok. Timestamp import coinyser. TypeCheckedTripleEquals import org. CharBuffer import java. Timestamp import cats. IO import org. SharedSparkSession import org. Timestamp import java. Instant import java. TimeUnit import cats. Expected: from,until, actual: FlatSpec import org. ConcurrentLinkedQueue import scala. ChannelPipeline import org. SocketChannel import org. NioClientSocketChannelFactory import org. Logging import org. JavaUtils import org.

StorageLevel import org. Random import org. ConfVars import org. WebDriver import org. HtmlUnitDriver import org. WebBrowser import org. Path import org. File import java. StandardCharsets import com. Files import org. FileUtils import org. YarnConfiguration import org. Matchers import org. ShuffleTestAccessor import org. StandardCharsets import java.

PrivilegedExceptionAction import java. UUID import org. SparkHadoopUtil import org. TimeZone import java. TimeUnit import org. WebApplicationException import org. KryoSerializer import org. TimeUnit import scala.



0コメント

  • 1000 / 1000