本文整理汇总了Scala中org.scalatest.mockito.MockitoSugar类的典型用法代码示例。如果您正苦于以下问题:Scala MockitoSugar类的具体用法?Scala MockitoSugar怎么用?Scala MockitoSugar使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MockitoSugar类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
}
}
}
示例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
}
}
示例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)
}
}
示例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)
}
}
}
示例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)
}
}
}
示例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)
}
}
}
示例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)
}
}
示例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)
}
示例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)))
// }
}
示例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 {
// }
}
示例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)))
}
}
示例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()
}
}
示例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()
}
}
示例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()
}
}
示例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) }
}
}
}