本文整理汇总了Scala中org.scalatest.mockito.MockitoSugar类的典型用法代码示例。如果您正苦于以下问题:Scala MockitoSugar类的具体用法?Scala MockitoSugar怎么用?Scala MockitoSugar使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MockitoSugar类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: ResultWriterTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.commons.output.writers
import java.io.File
import org.mockito.Mockito
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar
import scala.io.Source
class ResultWriterTest extends FunSpec with MockitoSugar {
describe("ResultWriter") {
val mockedResultWriter: ResultWriter = mock[ResultWriter]
it("should filterFilesByPrefix") {
val prefix = "ESB"
val firstResultFile = new File(s"${prefix}_results1.csv")
val secondResultFile = new File(s"${prefix}_results2.csv")
val otherFile = new File("other.csv")
val files = List(firstResultFile, secondResultFile, otherFile)
Mockito.doCallRealMethod().when(mockedResultWriter).filterFilesByPrefix(files, prefix)
val resultfiles = mockedResultWriter.filterFilesByPrefix(files, prefix)
assert(resultfiles.toSet.contains(firstResultFile))
assert(resultfiles.toSet.contains(secondResultFile))
}
it("should getIntermediateResultMaps") {
val csvContent =
"""column1,column2,column3
|value1,value2,value3""".stripMargin
val sources = List(Source.fromString(csvContent),
Source.fromString(csvContent))
Mockito.doCallRealMethod().when(mockedResultWriter).getIntermediateResultMaps(sources)
val resultMaps = mockedResultWriter.getIntermediateResultMaps(sources)
val expectedMap = Map[String, String](
"column1" -> "value1",
"column2" -> "value2",
"column3" -> "value3"
)
resultMaps.foreach(r => assert(r.toSet == expectedMap.toSet))
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:50,代码来源:ResultWriterTest.scala
示例2: TiledLayerTest
//设置package包名称以及导入依赖的类
package net.xylophones.frogger
import org.junit.runner.RunWith
import org.scalajs.dom.raw.HTMLImageElement
import org.scalatest.junit.JUnitRunner
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}
import org.mockito.Mockito._
@RunWith(classOf[JUnitRunner])
class TiledLayerTest extends FunSuite with Matchers with MockitoSugar with BeforeAndAfterEach {
val htmlImage = mock[HTMLImageElement]
val image = new Image(htmlImage)
when(htmlImage.width).thenReturn(20)
when(htmlImage.height).thenReturn(10)
val tiledImage = new TiledImage(image, 10, 10)
val tiles = Array(Array(Tile(0, 0, CellType.Deadly), Tile(1, 0, CellType.Deadly)))
val underTest = new TiledLayer(tiledImage, 1, 2, tiles)
test("TiledLayer contains Rectangles with correct local offset") {
val rects = underTest.rectangles
rects.size shouldBe 2
rects.head.x shouldBe 0
rects.head.y shouldBe 0
rects.last.x shouldBe 10
rects.last.y shouldBe 0
}
}
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:31,代码来源:TiledLayerTest.scala
示例3: createTiledImage
//设置package包名称以及导入依赖的类
package net.xylophones.frogger.test
import net.xylophones.frogger._
import org.mockito.Mockito.when
import org.scalajs.dom.raw.HTMLImageElement
import org.scalatest.mockito.MockitoSugar
trait FroggerTestSugar extends MockitoSugar {
def createTiledImage(width: Int, height: Int): TiledImage = {
val htmlImage = mock[HTMLImageElement]
val image = new Image(htmlImage)
when(htmlImage.width).thenReturn(20)
when(htmlImage.height).thenReturn(10)
new TiledImage(image, width, height)
}
def createSprite(width: Int, height: Int): Sprite = {
val spriteImage = mock[Image]
when(spriteImage.width).thenReturn(5)
when(spriteImage.height).thenReturn(5)
new Sprite(spriteImage, 5)
}
def createModel(channel: Channel, channelPosition: Vector): Model = {
val layers = Layers(
scoreTitle = mock[ScoreTitleLayer],
scoreLayer = mock[ScoreLayer],
scoreSpace = mock[BackgroundLayer],
homePlaceholder = mock[BackgroundLayer],
frog = mock[Sprite],
statusLayer = mock[StatusLayer],
timeLayer = mock[TimeLayer],
channels = Seq(channel),
homes = Seq(),
frogLayer = mock[FrogLayer]
)
val pos = layers.all.map(_ => channelPosition)
Model(layers=layers, positions = pos)
}
}
开发者ID:wjsrobertson,项目名称:scalajs-frogger,代码行数:46,代码来源:FroggerTestSugar.scala
示例4: CallbackTest
//设置package包名称以及导入依赖的类
package com.braxisltd.http
import com.braxisltd.http.HttpClient.{CallCancelledException, Callback}
import io.generators.core.Generators._
import org.apache.http.HttpResponse
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}
import scala.concurrent.Promise
class CallbackTest extends FlatSpec with Matchers with MockitoSugar with ScalaFutures {
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
val timeout = 100.millis
trait Fixture {
val unmarshalled = alphabetic10.next()
val httpResponse = mock[HttpResponse]
implicit val unmarshaller: HttpResponse => String = {
case resp if resp == httpResponse => unmarshalled
}
val promise = Promise[Response]()
val future = promise.future
val callback = new Callback(promise)
}
"Callback" should "complete the promise upon complete" in new Fixture {
callback.completed(httpResponse)
whenReady(future) {
_.entity[String] should be(unmarshalled)
}
}
it should "fail the future if the callback fails" in new Fixture {
val failureMessage = alphabetic10.next()
val exception = new Exception(failureMessage)
callback.failed(exception)
val recoveredWithFailureMessage = future.recover { case e => e.getMessage }
whenReady(recoveredWithFailureMessage) {
_ should be (failureMessage)
}
}
it should "fail the future if the callback is cancelled" in new Fixture {
callback.cancelled()
val recoveredWithFailureMessage = future.recover { case e => e.getClass.getName }
whenReady(recoveredWithFailureMessage) {
_ should be (CallCancelledException.getClass.getName)
}
}
}
开发者ID:braxisltd,项目名称:scala-apache-async-http,代码行数:55,代码来源:CallbackTest.scala
示例5: SendMetricsTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.datasender.metrics
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar
import org.hpi.esb.datasender.TestHelper.checkEquality
class SendMetricsTest extends FunSpec with MockitoSugar {
val expectedRecordNumber = 1000
val topicOffsets = Map("A" -> 10L, "B" -> 20L)
val sendMetrics = new SendMetrics(topicOffsets, expectedRecordNumber)
describe("getFailedSendsPercentage") {
it("should return 0 when expectedRecordNumber = 0") {
val failedSends = 100
val expectedRecordNumber = 0
val failedSendsResult = SendResult(expectedRecordNumber, failedSends)
assert(0.0 == failedSendsResult.failedSendsPercentage())
}
it("should calculate correctly") {
val failedSends = 10
val expectedRecordNumber = 100
val failedSendsResult = SendResult(expectedRecordNumber, failedSends)
assert(0.1 == failedSendsResult.failedSendsPercentage())
}
}
describe("getAccumulatedSendMetrics") {
val perTopicSendMetrics = Map("A" -> SendResult(expectedRecordNumber = 100L, failedSends = 10L),
"B" -> SendResult(expectedRecordNumber = 100L, failedSends = 5L))
val expectedAccumulatedSendMetrics = Map(
"expectedRecordNumber" -> 200L.toString,
"failedSends" -> 15L.toString,
"failedPercentage" -> 0.075.toString)
val accumulatedSendMetrics = sendMetrics.getAccumulatedSendResults(perTopicSendMetrics)
it("should calculate the correct overall stats") {
checkEquality[String, String](expectedAccumulatedSendMetrics, accumulatedSendMetrics)
checkEquality[String, String](accumulatedSendMetrics, expectedAccumulatedSendMetrics)
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:49,代码来源:SendMetricsTest.scala
示例6: DataSenderConfigTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.datasender.config
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar
class DataSenderConfigTest extends FunSpec with MockitoSugar {
val numberOfThreads = Option(1)
val singleColumnMode = false
describe("isNumberOfThreadsValid") {
it("should return false if number of threads is < 0") {
val numberOfThreads = Option(-1)
val config = DataSenderConfig(numberOfThreads, singleColumnMode)
assert(!config.isNumberOfThreadsValid)
}
it("should return false if number of threads is 0") {
val numberOfThreads = Option(0)
val config = DataSenderConfig(numberOfThreads, singleColumnMode)
assert(!config.isNumberOfThreadsValid)
}
it("should return true if number of threads is positive") {
val numberOfThreads = Option(1)
val config = DataSenderConfig(numberOfThreads, singleColumnMode)
assert(config.isNumberOfThreadsValid)
}
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:32,代码来源:DataSenderConfigTest.scala
示例7: TopicManagementTest
//设置package包名称以及导入依赖的类
package org.hpi.esb.util
import org.scalatest.FunSuite
import org.scalatest.mockito.MockitoSugar
import scala.collection.mutable
class TopicManagementTest extends FunSuite with MockitoSugar {
test("testGetMatchingTopics") {
val topicsToDelete = mutable.Buffer("ESB_IN_0", "ESB_OUT_O", "ESB_STATISTICS_0")
val topicsToKeep = mutable.Buffer("esb_new_IN_0", "esb_new_OUT_0", "esb_new_STATISTICS_0", "topic1", "topic2")
val allTopics = topicsToDelete ++ topicsToKeep
val prefix = "ESB_"
assert(allTopics.containsSlice(topicsToDelete))
assert(allTopics.containsSlice(topicsToKeep))
assert(allTopics.size == topicsToDelete.size + topicsToKeep.size)
assert(TopicManagement.getMatchingTopics(allTopics, prefix) == topicsToDelete)
}
}
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:23,代码来源:TopicManagementTest.scala
示例8: RulesSpec
//设置package包名称以及导入依赖的类
package hanabi
import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.ai._
import org.scalatest.prop.PropertyChecks
@RunWith(classOf[JUnitRunner])
class RulesSpec extends FlatSpec with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter
with PropertyChecks with HanabiDomain {
import SimpleRules._
import Cards._
"simple rules" should "have proper number of cards" in {
forAll { c: Card =>
whenever(c.level == 1) {
count(c) shouldBe 3
}
}
forAll { c: Card =>
whenever(c.level == 5) {
count(c) shouldBe 1
}
}
forAll { c: Card =>
whenever(c.level > 1 && c.level < 5) {
count(c) shouldBe 2
}
}
}
implicit override val generatorDrivenConfig = PropertyCheckConfiguration(
minSuccessful = 100,
maxDiscardedFactor = 15)
}
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:43,代码来源:RulesSpec.scala
示例9: PlayerSpec
//设置package包名称以及导入依赖的类
package hanabi
import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.ai._
@RunWith(classOf[JUnitRunner])
class PlayerSpec extends FlatSpec with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter {
import SimpleRules._
val player = new Player {
def nextMove(s: GameState) = ???
}
val onesToThrees = allCards.filter(_.level < 4)
val foursFives = allCards.filter(_.level >= 4)
val (fives, allExceptFives) = allCards.partition(_.level == 5)
"a player" should "guess its possible cards with no clues" in {
val possible = player.possibleCards(allExceptFives, 5)
for (p <- 0 to 4)
possible(p) should contain theSameElementsAs fives
}
it should "guess its possible cards with a single clue" in {
val possible = player.possibleCards(onesToThrees, 5, Seq(LevelClue(level = 5, position = 3)))
possible(1) should contain theSameElementsAs allCards.filter(_.level == 5)
}
val clues = Seq(
LevelClue(position = 3, level = 5),
ColorClue(position = 3, color = Blue))
it should "guess its possible cards with a 2 clues on the same card" in {
val possible = player.possibleCards(onesToThrees, 5, clues)
possible(3) should contain theSameElementsAs Seq(Card(5, Blue))
}
// it should "guess its possible cards with a 2 clues on another card" in {
// player.possibleCards(4, onesToThrees, clues) should
// contain theSameElementsAs (foursFives diff Seq(Card(5, Blue)))
// }
}
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:51,代码来源:PlayerSpec.scala
示例10: DeckSpec
//设置package包名称以及导入依赖的类
package hanabi
import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.Card._
import hanabi.ai._
import SimpleRules._
@RunWith(classOf[JUnitRunner])
class DeckSpec extends FlatSpec
with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter
with StackedDeck {
"a Deck" should "distribute cards one by one" in {
val (h, rest) = Deck(allCards.distinct).deal(hands = 5, cardsPerHand = 5)
val hnds = h.toVector
println(hnds)
def expected(lvl: Int) = allColors.map(c => Card(lvl, c)).toVector
for {
h <- 0 until 5
(c, i) <- hnds(h).cards.zipWithIndex
} c.level should be(5 - i)
}
// it should "allow to try to draw from an empty deck an return unchanged deck" in {
// }
}
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:37,代码来源:DeckSpec.scala
示例11: HandSpec
//设置package包名称以及导入依赖的类
package hanabi
import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.Card._
import hanabi.ai._
import SimpleRules._
import Cards._
@RunWith(classOf[JUnitRunner])
class HandSpec extends FlatSpec
with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter {
"a Hand" should "convert color hints to clues" in {
val h = Hand(2 R, 2 G, 3 B, 1 Y)
val (clued, clues) = h.hint(Blue)
h.clues shouldBe empty
clued.clues shouldBe (Vector(ColorClue(Blue, 2)))
clues shouldBe (Vector(ColorClue(Blue, 2)))
}
it should "convert level hints to clues" in {
val h = Hand(2 R, 2 G, 3 B, 1 Y)
val (clued, clues) = h.hint(2)
clued.clues shouldBe (Vector(LevelClue(2, 0), LevelClue(2, 1)))
clues shouldBe (Vector(LevelClue(2, 0), LevelClue(2, 1)))
}
}
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:38,代码来源:HandSpec.scala
示例12: TestObjectDownload
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4
import akka.util.ByteString
import com.squareup.okhttp.mockwebserver.{MockResponse, MockWebServer}
import edu.goldlok.minio_scala.mio.MioClient
import okio.Buffer
import org.scalatest.{FlatSpec, Matchers}
import org.scalatest.mockito.MockitoSugar
import scala.concurrent.Await
class TestObjectDownload extends FlatSpec with Matchers with MockitoSugar {
import edu.goldlok.minio_scala.s3v4.TestElem._
private def getDownloadSever(body: String): MockWebServer = {
val server = new MockWebServer()
val response = new MockResponse()
response.addHeader(CONTENT_LENGTH, "5080")
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM)
response.addHeader("ETag", MD5_HASH_STRING)
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT)
response.setResponseCode(200)
response.setBody(new Buffer().writeUtf8(body))
server.enqueue(response)
server.start()
server
}
private def testGetObject2Source() = {
val expectedObject = HELLO_WORLD
val server = getDownloadSever(expectedObject)
val source = MioClient(server.getHostName, server.getPort, keys).getObject(BUCKET, OBJECT)
val httpResponse = Await.result(source, timeout)
val body = httpResponse.runFold(ByteString.empty)(_ ++ _)
val content = Await.result(body, timeout)
content.utf8String should be(expectedObject)
server.shutdown()
}
"download object " should "return " in {
testGetObject2Source()
}
}
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:46,代码来源:TestObjectDownload.scala
示例13: TestPutObject
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets
import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.squareup.okhttp.mockwebserver.{MockResponse, MockWebServer}
import edu.goldlok.minio_scala.mio.MioClient
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}
import scala.concurrent.Await
class TestPutObject extends FlatSpec with Matchers with MockitoSugar {
import edu.goldlok.minio_scala.s3v4.TestElem._
private def obtPutObjectServer(): MockWebServer = {
val server = new MockWebServer()
val response = new MockResponse()
response.addHeader("Date", MON_29_JUN_2015_22_01_10_GMT)
response.addHeader(LAST_MODIFIED, MON_04_MAY_2015_07_58_51_GMT)
response.addHeader("ETag", MD5_HASH_STRING)
response.setResponseCode(200)
server.enqueue(response)
server.start()
server
}
private def testPutObject() = {
val server = obtPutObjectServer()
val source = Source.single(ByteString(HELLO_WORLD))
val response = MioClient(server.getHostName, server.getPort, keys).putObject(BUCKET, OBJECT, source, HELLO_WORLD.length)
val uploadResult = Await.result(response, timeout)
uploadResult.isSuccess should be (true)
server.shutdown()
}
private def testPutObjectByStream() = {
val server = obtPutObjectServer()
val stream = new ByteArrayInputStream(HELLO_WORLD.getBytes(StandardCharsets.UTF_8))
val response = MioClient(server.getHostName, server.getPort, keys).putObject(BUCKET, OBJECT, stream, HELLO_WORLD.length)
val uploadResult = Await.result(response, timeout)
uploadResult.isSuccess should be (true)
server.shutdown()
}
"put object " should "return" in {
testPutObject()
testPutObjectByStream()
}
}
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:54,代码来源:TestPutObject.scala
示例14: TestListBuckets
//设置package包名称以及导入依赖的类
package edu.goldlok.minio_scala.s3v4
import java.text.SimpleDateFormat
import java.util.TimeZone
import com.squareup.okhttp.mockwebserver.{MockResponse, MockWebServer}
import edu.goldlok.minio_scala.mio.MioClient
import okio.Buffer
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}
import scala.concurrent.Await
class TestListBuckets extends FlatSpec with Matchers with MockitoSugar {
import edu.goldlok.minio_scala.s3v4.TestElem._
val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
private val bucketCreateTime = Map("bucket" -> dateFormat.parse("2015-05-05T20:35:51.410Z"),
"foo" -> dateFormat.parse("2015-05-05T20:35:47.170Z"))
private val entity = "<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\">" +
"<Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><Buckets><Bucket><Name>bucket</Name>" +
"<CreationDate>2015-05-05T20:35:51.410Z</CreationDate></Bucket><Bucket><Name>foo</Name>" +
"<CreationDate>2015-05-05T20:35:47.170Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>"
private def obtListBucketServer(): MockWebServer = {
val server = new MockWebServer()
val response = new MockResponse()
response.addHeader("Date", MON_29_JUN_2015_22_01_10_GMT)
response.addHeader(CONTENT_LENGTH, "351")
response.addHeader(CONTENT_TYPE, "application/xml")
response.setBody(new Buffer().writeUtf8(entity))
response.setResponseCode(200)
server.enqueue(response)
server.start()
server
}
private def testListBucket() = {
val server = obtListBucketServer()
val response = MioClient(server.getHostName, server.getPort, keys).listBuckets()
val listResult = Await.result(response, timeout)
listResult.isSuccess should be (true)
listResult.buckets foreach { elem =>
bucketCreateTime.contains(elem.name) should be (true)
val date = bucketCreateTime.get(elem.name)
date.get should be (elem.creationDate)
}
}
"list buckets " should "return" in {
testListBucket()
}
}
开发者ID:TopSpoofer,项目名称:minio-scala,代码行数:58,代码来源:TestListBuckets.scala
示例15: equalTo
//设置package包名称以及导入依赖的类
package mesosphere.marathon.test
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.{ Answer, OngoingStubbing }
import org.mockito.verification.VerificationMode
import org.mockito.{ Mockito => M }
import org.scalatest.mockito.MockitoSugar
trait Mockito extends MockitoSugar {
def equalTo[T](t: T) = org.mockito.Matchers.eq(t)
def eq[T](t: T) = org.mockito.Matchers.eq(t)
def any[T] = org.mockito.Matchers.any[T]
def anyBoolean = org.mockito.Matchers.anyBoolean
def anyString = org.mockito.Matchers.anyString
def same[T](value: T) = org.mockito.Matchers.same(value)
def verify[T](t: T, mode: VerificationMode = times(1)) = M.verify(t, mode)
def times(num: Int) = M.times(num)
def timeout(millis: Int) = M.timeout(millis.toLong)
def atLeastOnce = M.atLeastOnce()
def once = M.times(1)
def atLeast(num: Int) = M.atLeast(num)
def atMost(num: Int) = M.atMost(num)
def never = M.never()
def inOrder(mocks: AnyRef*) = M.inOrder(mocks: _*)
def noMoreInteractions(mocks: AnyRef*): Unit = {
M.verifyNoMoreInteractions(mocks: _*)
}
def reset(mocks: AnyRef*): Unit = {
M.reset(mocks: _*)
}
class MockAnswer[T](function: Array[AnyRef] => T) extends Answer[T] {
def answer(invocation: InvocationOnMock): T = {
function(invocation.getArguments)
}
}
implicit class Stubbed[T](c: => T) {
def returns(t: T, t2: T*): OngoingStubbing[T] = {
if (t2.isEmpty) M.when(c).thenReturn(t)
else t2.foldLeft (M.when(c).thenReturn(t)) { (res, cur) => res.thenReturn(cur) }
}
def answers(function: Array[AnyRef] => T) = M.when(c).thenAnswer(new MockAnswer(function))
def throws[E <: Throwable](e: E*): OngoingStubbing[T] = {
if (e.isEmpty) throw new java.lang.IllegalArgumentException("The parameter passed to throws must not be empty")
e.drop(1).foldLeft(M.when(c).thenThrow(e.head)) { (res, cur) => res.thenThrow(cur) }
}
}
}
开发者ID:xiaozai512,项目名称:marathon,代码行数:55,代码来源:Mockito.scala
示例16: CameraRelayControllerTest
//设置package包名称以及导入依赖的类
package controllers
import com.intersection.camerarelay.UploadManager
import org.mockito.Matchers._
import org.scalatest.concurrent.{Futures, ScalaFutures}
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
import play.api.libs.Files
import play.api.mvc.{Request, Result}
import play.api.test.FakeRequest
import play.api.test.Helpers._
import org.mockito.Mockito._
import scala.concurrent.Future
class CameraRelayControllerTest extends FunSpec with Matchers with MockitoSugar with BeforeAndAfter with Futures with ScalaFutures {
var controller : CameraRelayController = _
var uploadManager : UploadManager = _
before {
uploadManager = mock[UploadManager]
controller = new CameraRelayController(uploadManager)
}
describe(classOf[CameraRelayControllerTest].getName) {
it("Rejects requests without a valid siteId header : X-Site-Id") {
val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
val result = controller.uploadVideoChunk().apply(request)
status(result) should equal(400)
}
it("Rejects requests without a valid Link-Time header : X-Link-Time") {
val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234")).withBody(Files.TemporaryFile())
val result: Future[Result] = controller.uploadVideoChunk().apply(request)
status(result) should equal(400)
}
it("Accepts a fully formed request") {
import scala.concurrent.ExecutionContext.Implicits.global
when(uploadManager.handleVideoChunk(any[String],any[String],any[Files.TemporaryFile])).thenReturn(Future(()))
val request: Request[Files.TemporaryFile] = FakeRequest().withHeaders(("Content-Type"->"application/octet-stream"), ("X-Site-Id"->"mn-1234"), ("X-Link-Time"->"2016-12-12")).withBody(Files.TemporaryFile())
val result: Future[Result] = controller.uploadVideoChunk().apply(request)
status(result) should equal(202)
}
}
}
开发者ID:arjunmukherjee,项目名称:camerarelay,代码行数:48,代码来源:CameraRelayControllerTest.scala
示例17: UserRepositorySpec
//设置package包名称以及导入依赖的类
package org.cristal.repository
import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, TestKit}
import akka.util.Timeout
import com.github.t3hnar.bcrypt._
import org.cristal.model.{NewUser, User}
import org.cristal.repository.UserRepository.UserCreated
import org.cristal.repository.dao.UserDAO
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito.when
import org.scalatest.concurrent.Eventually
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.concurrent.Future
import scala.concurrent.duration._
class UserRepositorySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll with Eventually with MockitoSugar {
implicit val duration: Timeout = 10 seconds
def this() = this(ActorSystem("UserRepositorySpecSystem"))
override def afterAll {
TestKit.shutdownActorSystem(system)
}
"An UserRepository Actor" should {
"Create a new user" in {
val userDAO = mock[UserDAO]
val passowod = "my_password"
val encryptedPassword = passowod.bcrypt
when(userDAO.insert(any())).thenReturn(Future.successful(()))
val userRepository = system.actorOf(UserRepository.props(userDAO))
val newUser = NewUser("name", passowod, "[email protected]", "John", "Doe")
userRepository ! UserRepository.CreateUser(newUser, self)
expectMsgPF() {
case UserCreated(User("name", encryptedPassword, "[email protected]", "John", "Doe")) => ()
}
}
}
}
开发者ID:frecano,项目名称:cristal,代码行数:43,代码来源:UserRepositorySpec.scala
示例18: ConfigServiceResolverTest
//设置package包名称以及导入依赖的类
package csw.services.config.client.internal
import java.net.URI
import csw.services.config.client.commons.ConfigServiceConnection
import csw.services.config.client.scaladsl.ConfigClientFactory
import csw.services.location.models.HttpLocation
import csw.services.location.scaladsl.{LocationService, LocationServiceFactory}
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FunSuite, Matchers}
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
class ConfigServiceResolverTest extends FunSuite with Matchers with MockitoSugar {
private val actorRuntime = new ActorRuntime()
import actorRuntime._
test("should throw exception if not able to resolve config service http server") {
val locationService = LocationServiceFactory.make()
val configService = ConfigClientFactory.adminApi(actorSystem, locationService)
val exception = intercept[RuntimeException] {
Await.result(configService.list(), 7.seconds)
}
exception.getMessage shouldEqual s"config service connection=${ConfigServiceConnection.value.name} can not be resolved"
}
test("should give URI for resolved config service") {
val mockedLocationService = mock[LocationService]
val uri = new URI(s"http://config-host:4000")
val resolvedConfigLocation = Future(Some(HttpLocation(ConfigServiceConnection.value, uri)))
when(mockedLocationService.resolve(ConfigServiceConnection.value, 5.seconds)).thenReturn(resolvedConfigLocation)
val configServiceResolver = new ConfigServiceResolver(mockedLocationService, actorRuntime)
val actualUri = Await.result(configServiceResolver.uri, 2.seconds)
actualUri.toString() shouldEqual uri.toString
}
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:44,代码来源:ConfigServiceResolverTest.scala
示例19: StubbedHcdBehaviorTest
//设置package包名称以及导入依赖的类
package csw.common.framework.scaladsl.hcd
import akka.typed.testkit.StubbedActorContext
import akka.typed.testkit.scaladsl.TestProbe
import csw.common.components.hcd.HcdDomainMsg
import csw.common.framework.internal.ComponentBehavior
import csw.common.framework.models.IdleMsg.Initialize
import csw.common.framework.models.InitialMsg.Run
import csw.common.framework.models.SupervisorIdleMsg.{InitializeFailure, Initialized, Running}
import csw.common.framework.models.{ComponentMsg, FromComponentLifecycleMessage}
import csw.common.framework.scaladsl.{ComponentHandlers, FrameworkComponentTestSuite}
import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import scala.concurrent.Future
class StubbedHcdBehaviorTest extends FrameworkComponentTestSuite with MockitoSugar {
test("hcd component should send initialize and running message to supervisor") {
val sampleHcdHandler = mock[ComponentHandlers[HcdDomainMsg]]
when(sampleHcdHandler.initialize()).thenReturn(Future.unit)
val supervisorProbe: TestProbe[FromComponentLifecycleMessage] = TestProbe[FromComponentLifecycleMessage]
val ctx = new StubbedActorContext[ComponentMsg]("test-component", 100, system)
val componentBehavior = new ComponentBehavior[HcdDomainMsg](ctx, supervisorProbe.ref, sampleHcdHandler)
ctx.selfInbox.receiveMsg() shouldBe Initialize
componentBehavior.onMessage(Initialize)
Thread.sleep(100)
supervisorProbe.expectMsgType[Initialized]
verify(sampleHcdHandler).initialize()
componentBehavior.onMessage(Run)
supervisorProbe.expectMsgType[Running]
verify(sampleHcdHandler).onRun()
verify(sampleHcdHandler).isOnline_=(true)
}
test("A Hcd component should send InitializationFailure message if it fails in initialization") {
val sampleHcdHandler = mock[ComponentHandlers[HcdDomainMsg]]
val exceptionReason = "test Exception"
when(sampleHcdHandler.initialize()).thenThrow(new RuntimeException(exceptionReason))
val supervisorProbe: TestProbe[FromComponentLifecycleMessage] = TestProbe[FromComponentLifecycleMessage]
val ctx = new StubbedActorContext[ComponentMsg]("test-component", 100, system)
val componentBehavior = new ComponentBehavior[HcdDomainMsg](ctx, supervisorProbe.ref, sampleHcdHandler)
ctx.selfInbox.receiveMsg() shouldBe Initialize
componentBehavior.onMessage(Initialize)
val initializationFailure = supervisorProbe.expectMsgType[InitializeFailure]
initializationFailure.reason shouldBe exceptionReason
}
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:61,代码来源:StubbedHcdBehaviorTest.scala
示例20: MainTest
//设置package包名称以及导入依赖的类
import org.scalatest.Matchers._
import org.scalatest.WordSpec
import org.scalatest.mockito.MockitoSugar
class MainTest extends WordSpec with MockitoSugar {
private def theParameters = afterWord("the parameters")
val noArguments = Array.empty[String]
val expectedArguments = Array(getClass.getResource("test.txt").getFile)
"The main execution" when theParameters {
"are empty" should {
"throw an IllegalArgumentException" in {
intercept[IllegalArgumentException](Main.checkIfIsValid(noArguments))
}
}
"have an existing filename as first argument" should {
"continue without problems" in {
Main.checkIfIsValid(expectedArguments)
}
}
}
}
开发者ID:camilosampedro,项目名称:PSP-TDD,代码行数:25,代码来源:MainTest.scala
注:本文中的org.scalatest.mockito.MockitoSugar类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论