• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala when类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.mockito.Mockito.when的典型用法代码示例。如果您正苦于以下问题:Scala when类的具体用法?Scala when怎么用?Scala when使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了when类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: RefcountedServiceTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.service

import com.twitter.util._
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito.{times, verify, when}
import org.mockito.{Matchers, Mockito}
import org.mockito.Matchers._
import com.twitter.finagle.Service

@RunWith(classOf[JUnitRunner])
class RefcountedServiceTest extends FunSuite with MockitoSugar {

  class PoolServiceWrapperHelper {
    val service = mock[Service[Any, Any]]
    when(service.close(any)) thenReturn Future.Done
    val promise = new Promise[Any]
    when(service(Matchers.any)) thenReturn promise
    val wrapper = Mockito.spy(new RefcountedService[Any, Any](service))
  }

  test("PoolServiceWrapper should call release() immediately when no requests have been made") {
    val h = new PoolServiceWrapperHelper
    import h._

    verify(service, times(0)).close(any)
    wrapper.close()
    verify(service).close(any)
  }

  test("PoolServiceWrapper should call release() after pending request finishes") {
    val h = new PoolServiceWrapperHelper
    import h._

    val f = wrapper(123)
    assert(!f.isDefined)
    verify(service)(123)

    wrapper.close()
    verify(service, times(0)).close(any)

    promise() = Return(123)
    verify(service).close(any)
    assert(f.isDefined)
    assert(Await.result(f) == 123)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:RefcountedServiceTest.scala


示例2: 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


示例3: 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


示例4: NetworkTest

//设置package包名称以及导入依赖的类
package se.andrisak.backprop.algo

import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}

import scala.util.Random


class NetworkTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val RANDOM_VALUE = 0.2
  val INPUT_LAYER_NEURON_COUNT = 1
  val HIDDEN_LAYER_NEURON_COUNT = 1
  val INPUT = 0.528593

  val random = mock[Random]
  when(random.nextDouble()).thenReturn(RANDOM_VALUE)

  test("test that clearInput clears all node input") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
    network.getInputLayer.neurons.head.addInput(0.534543)
    network.getHiddenLayer.neurons.head.addInput(0.6854543)
    network.clearInputs()

    network.getInputLayer.neurons.head.getInput should equal(0.0)
    network.getHiddenLayer.neurons.head.getInput should equal(0.0)
  }

  test("init of input layer should add the input to input neurons") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
    network.initInputLayer(List(INPUT))

    network.getInputLayer.neurons.head.getInput should equal(INPUT)
  }

  test("adding more input values than input neurons should throw an exception") {
    val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)

    intercept[IllegalArgumentException] {
      network.initInputLayer(List(INPUT, INPUT))
    }
  }
} 
开发者ID:andrisak,项目名称:backprop,代码行数:44,代码来源:NetworkTest.scala


示例5: NeuronTest

//设置package包名称以及导入依赖的类
package se.andrisak.backprop.algo

import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}

import scala.util.Random


class NeuronTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
  val NEURON_NAME = "neuron"
  val NEURON_NAME2 = "neuron2"
  val RANDOM_VALUE = 0.53
  val random = mock[Random]
  when(random.nextDouble()).thenReturn(RANDOM_VALUE)
  val neuron = new Neuron(NEURON_NAME, random)

  test("input should be stored and be cleared") {
    val input = 0.543
    neuron.addInput(input)

    neuron.getInput should equal (input)
    neuron.clearInput()
    neuron.getInput should equal (0)
  }

  test("neurons should be connected with a ForwardLink") {
    val neuron2 = new Neuron(NEURON_NAME2, random)

    neuron.connectToNeuronsInLayer(List(neuron2))

    val link = neuron.getLinkTo(neuron2)
    link.to should equal(neuron2)
    link.weight should equal(RANDOM_VALUE)
    link should equal(neuron.getNextLayerLinks.head)
  }

  test("neurons should be connected with a ReverseLink") {
    val neuron2 = new Neuron(NEURON_NAME2, random)

    neuron.connectToNeuronsInPreviousLayer(List(neuron2))

    neuron.getPreviousLayerNeurons.head should equal(neuron2)
  }

  test("test the sigmoid computation") {
    neuron.output should equal(0.5)
  }

} 
开发者ID:andrisak,项目名称:backprop,代码行数:51,代码来源:NeuronTest.scala


示例6: DatabaseReaderActivitySpec

//设置package包名称以及导入依赖的类
package test.yumi.pipeline.activities

import java.util.Properties

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions
import org.mockito.Mockito.{verify, when}
import test.yumi.pipeline.MockSessionSpec
import yumi.YumiMap
import yumi.pipeline.activities.DatabaseReaderActivity

class DatabaseReaderActivitySpec extends MockSessionSpec {

  it should "load sql server table as spark view" in new MockSessionScope {

    // Arrange
    val url = "url"
    val table = "table_name"
    val as = "as"
    val driver = "com.mysql.Driver"
    val properties = Map("batchSize" -> "2000")
    val expectedProperties = new Properties()
    properties.foreach {
      case (key, value) =>
        expectedProperties.setProperty(key, value)
    }
    expectedProperties.put(JDBCOptions.JDBC_DRIVER_CLASS, driver)

    val parameters = createParameters()
      .add("url", url)
      .add("table", table)
      .add("driver", driver)
      .add("as", as)
      .add("properties", properties)
      .build()
    val sessionData = YumiMap()
    val dataFrame = mock[DataFrame]

    when(dataFrameReader.jdbc(any[String], any[String], any[Properties])).thenReturn(dataFrame)

    // Act
    val activity = new DatabaseReaderActivity(parameters)
    val resultSessionData = activity.invoke(sessionData)

    // Assert
    verify(sparkSession).read
    verify(dataFrameReader)
      .jdbc(url, table, expectedProperties)
    verify(dataFrame).createTempView(as)

    resultSessionData === sessionData
  }
} 
开发者ID:coderdiaries,项目名称:yumi,代码行数:54,代码来源:DatabaseReaderActivitySpec.scala


示例7: DatabaseWriterActivitySpec

//设置package包名称以及导入依赖的类
package test.yumi.pipeline.activities

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.execution.datasources.jdbc.JDBCOptions
import org.mockito.Mockito.{verify, when}
import test.yumi.pipeline.MockSessionSpec
import yumi.YumiMap
import yumi.pipeline.activities.DatabaseWriterActivity

class DatabaseWriterActivitySpec extends MockSessionSpec {

  it should "write to database table from spark view" in new MockSessionScope {

    // Arrange
    val url = "jdbc:postgresql://yumi.rds.amazonaws.com:5432/yumi_postgresql?user=yumi&password=somepassword"
    val table = "table_name"
    val as = "as"
    val mode = "append"
    val jdbcDriverClass = "org.postgresql.Driver"
    val properties = Map("batchSize" -> "2000")

    val completeOptions: Map[String, String] = properties +
      (JDBCOptions.JDBC_TABLE_NAME -> as) +
      (JDBCOptions.JDBC_DRIVER_CLASS -> jdbcDriverClass) +
      ("url" -> url)

    val parameters = createParameters()
      .add("url", url)
      .add("table", table)
      .add("as", as)
      .add("properties", properties)
      .add("mode", mode)
      .add("driver", jdbcDriverClass)
      .build()
    val sessionData = YumiMap()
    val dataFrame = mock[DataFrame]

    when(sparkSession.table(table)).thenReturn(dataFrame)

    // Act
    val activity = new DatabaseWriterActivity(parameters)
    val resultSessionData = activity.invoke(sessionData)

    // Assert
    verify(dataFrameWriter).write(dataFrame, "jdbc:postgresql", mode, url, completeOptions)

    resultSessionData === sessionData
  }
} 
开发者ID:coderdiaries,项目名称:yumi,代码行数:50,代码来源:DatabaseWriterActivitySpec.scala


示例8: ExceptionSourceFilterTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.filter

import com.twitter.finagle.{Service, SourcedException, Failure}
import com.twitter.util.{Await, Future}

import org.junit.runner.RunWith

import org.mockito.Matchers.anyInt
import org.mockito.Mockito.when
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ExceptionSourceFilterTest extends FunSuite with MockitoSugar {
  test("ExceptionSourceFilter should add a name to sourced exceptions") {
    val service = mock[Service[Int, Int]]
    val e = new SourcedException{}
    when(service(anyInt)).thenReturn(Future.exception(e))
    val composed = new ExceptionSourceFilter("name") andThen service
    val actual = intercept[SourcedException] {
      Await.result(composed(0))
    }
    assert(actual.serviceName == "name")
  }

  test("ExceptionSourceFilter should add a name to failures") {
    val service = mock[Service[Int, Int]]
    val e = new Failure("everything sucks")
    when(service(anyInt)).thenReturn(Future.exception(e))
    val composed = new ExceptionSourceFilter("name") andThen service
    val actual = intercept[Failure] {
      Await.result(composed(0))
    }
    assert(actual.getSource(Failure.Source.Service) == Some("name"))
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:38,代码来源:ExceptionSourceFilterTest.scala


示例9: StatsFactoryWrapperTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.factory

import com.twitter.finagle.{ClientConnection, ServiceFactory}
import com.twitter.finagle.stats.InMemoryStatsReceiver
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.mockito.Matchers.any
import org.mockito.Mockito.{verify, when}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class StatsFactoryWrapperTest extends FunSuite with MockitoSugar {
  val underlying = mock[ServiceFactory[Int, Int]]
  val rex = new RuntimeException
  val t = new Throwable(rex)

  test("report exceptions on Service creation failure") {
    val receiver = new InMemoryStatsReceiver
    val statsFac = new StatsFactoryWrapper(underlying, receiver)

    when(underlying(any[ClientConnection])) thenReturn Future.exception(t)

    intercept[Throwable] {
      Await.result(statsFac(ClientConnection.nil))
    }

    val expected = Map(
      List("failures", t.getClass.getName, rex.getClass.getName) -> 1)
    assert(receiver.counters == expected)
    verify(underlying)(ClientConnection.nil)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:35,代码来源:StatsFactoryWrapperTest.scala


示例10: OptionallyServableFilterTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.service

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import com.twitter.finagle.{NotServableException, Service}
import org.mockito.Mockito.{times, verify, when}
import org.mockito.Matchers._
import com.twitter.util.{Await, Future}

@RunWith(classOf[JUnitRunner])
class OptionallyServableFilterTest extends FunSuite with MockitoSugar {

  class OptionnallyServableFilterHelper {
    val underlying = mock[Service[String, String]]
    when(underlying.close(any)) thenReturn Future.Done

    val fn = mock[String => Future[Boolean]]
    val service = new OptionallyServableFilter(fn) andThen underlying
    val request = "request"
    val response = Future.value("response")
  }

  test("OptionallyServableFilter should passes through when fn returns true") {
    val h = new OptionnallyServableFilterHelper
    import h._

    when(fn.apply(request)) thenReturn Future.value(true)
    when(underlying(request)) thenReturn response
    assert(Await.result(service(request)) == Await.result(response))

    verify(fn).apply(request)
  }

  test("OptionallyServableFilter should throws NotServableException when fn returns false") {
    val h = new OptionnallyServableFilterHelper
    import h._

    when(fn.apply(request)) thenReturn Future.value(false)

    intercept[NotServableException] {
      Await.result(service(request))
    }
    verify(underlying, times(0)).apply(any[String])
    verify(fn).apply(request)
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:OptionallyServableFilterTest.scala


示例11: CloseOnReleaseServiceTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.service

import org.junit.runner.RunWith
import org.mockito.Mockito.{verify, when, times}
import org.mockito.Matchers._
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import com.twitter.finagle.{WriteException, Service, Status}
import com.twitter.util.{Await, Promise, Future}

@RunWith(classOf[JUnitRunner])
class CloseOnReleaseServiceTest extends FunSuite with MockitoSugar {

  class Helper {
    val service = mock[Service[Any, Any]]
    when(service.close(any)) thenReturn Future.Done
    val promise = new Promise[Any]
    when(service(any)) thenReturn promise
    when(service.status) thenReturn Status.Open
    val wrapper = new CloseOnReleaseService(service)
  }

  test("only call release on the underlying service once") {
    val h = new Helper
    import h._
    
    assert(wrapper.isAvailable)
    verify(service, times(1)).status

    wrapper.close()
    verify(service, times(1)).close(any)
    wrapper.close()
    verify(service, times(1)).close(any)
    
    assert(!wrapper.isAvailable)
    verify(service, times(1)).status
  }

  test("throw a write exception if we attempt to use a released service") {
    val h = new Helper
    import h._

    wrapper.close()
    intercept[WriteException] {
      Await.result(wrapper(132))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:50,代码来源:CloseOnReleaseServiceTest.scala


示例12: MemorySpaceTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mux.lease.exp

import com.twitter.conversions.storage.intToStorageUnitableWholeNumber
import com.twitter.util.StorageUnit
import org.mockito.Mockito.{when, verify}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class MemorySpaceTest extends FunSuite with MockitoSugar {
  test("MemorySpace#left should find the number of bytes left before we hit minDiscount") {
    val nfo = mock[JvmInfo]
    when(nfo.remaining()).thenReturn(10.megabytes)
    val range = StorageUnit.zero
    val minDiscount = 5.megabytes
    val maxDiscount = StorageUnit.zero
    val rSnooper = mock[RequestSnooper]
    val space = new MemorySpace(nfo, minDiscount, maxDiscount, rSnooper)
    assert(space.left == 5.megabytes)
    verify(nfo).remaining()
  }

  test("MemorySpace should be able to compute a discount correctly") {
    val nfo = mock[JvmInfo]
    val minDiscount = 5.megabytes
    val maxDiscount = 10.megabytes
    val rSnooper = mock[RequestSnooper]
    when(rSnooper.handleBytes()).thenReturn(2.megabytes)
    val rnd = mock[GenerationalRandom]
    when(rnd.apply()).thenReturn(107.megabytes.inBytes.toInt)
    val space =
      new MemorySpace(nfo, minDiscount, maxDiscount, rSnooper, NullLogsReceiver, rnd)
    assert(space.discount() == 7.megabytes)
    verify(rnd).apply()
    verify(rSnooper).handleBytes()
  }

  test("MemorySpace should be able to default to a max") {
    val nfo = mock[JvmInfo]
    val minDiscount = 5.megabytes
    val maxDiscount = 8.megabytes
    val rSnooper = mock[RequestSnooper]
    when(rSnooper.handleBytes()).thenReturn(9.megabytes)
    val rnd = mock[GenerationalRandom]
    val space =
      new MemorySpace(nfo, minDiscount, maxDiscount, rSnooper, NullLogsReceiver, rnd)
    assert(space.discount() == 8.megabytes)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:52,代码来源:MemorySpaceTest.scala


示例13: GenerationalRandomTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mux.lease.exp

import org.junit.runner.RunWith
import org.mockito.Mockito.{when, verify, times}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import scala.util.Random

@RunWith(classOf[JUnitRunner])
class GenerationalRandomTest extends FunSuite with MockitoSugar {
  test("GenerationalRandom stays the same intragenerationally") {
    val nfo = mock[JvmInfo]
    when(nfo.generation()).thenReturn(0)
    val rnd = new Random(12334)
    val gen = new GenerationalRandom(nfo, rnd)
    verify(nfo).generation()

    val x = gen()
    verify(nfo, times(2)).generation()

    assert(gen() == x)
    verify(nfo, times(3)).generation()
  }

  test("GenerationalRandom changes intergenerationally") {
    val nfo = mock[JvmInfo]
    when(nfo.generation()).thenReturn(0)
    val rnd = new Random(12334)
    val gen = new GenerationalRandom(nfo, rnd)
    verify(nfo).generation()

    val x = gen()
    verify(nfo, times(2)).generation()

    assert(gen() == x)
    verify(nfo, times(3)).generation()

    when(nfo.generation()).thenReturn(1)

    assert(gen() != x)
    verify(nfo, times(5)).generation()
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:45,代码来源:GenerationalRandomTest.scala


示例14: RequestSnooperTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.mux.lease.exp

import com.twitter.util.{Time, MockTimer}
import com.twitter.conversions.time.intToTimeableNumber
import com.twitter.conversions.storage.intToStorageUnitableWholeNumber
import org.junit.runner.RunWith
import org.mockito.Mockito.when
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class RequestSnooperTest extends FunSuite with MockitoSugar {
  test("RequestSnooper should compute handleBytes reasonably") {
    val ctr = mock[ByteCounter]
    val quantile = 0.50

    when(ctr.rate()).thenReturn(1)

    Time.withCurrentTimeFrozen { ctl =>
      when(ctr.lastGc).thenReturn(Time.now - 5.seconds)

      val tmr = new MockTimer()
      val snooper = new RequestSnooper(ctr, quantile, timer = tmr)
      for (_ <- 0 until 50)
        snooper.observe(1.second)
      for (_ <- 0 until 50)
        snooper.observe(2.seconds)
      for (_ <- 0 until 50)
        snooper.observe(3.seconds)
      ctl.advance(12.seconds)
      tmr.tick()
      assert(snooper.handleBytes() == 2000.bytes)
    }
  }

  test("RequestSnooper should discard results that overlap with a gc") {
    val ctr = mock[ByteCounter]
    val quantile = 0.50

    when(ctr.rate()).thenReturn(1)

    Time.withCurrentTimeFrozen { ctl =>
      when(ctr.lastGc).thenReturn(Time.now - 5.seconds)

      val tmr = new MockTimer()
      val snooper = new RequestSnooper(ctr, quantile, timer = tmr)
      for (_ <- 0 until 50)
        snooper.observe(1.second)
      for (_ <- 0 until 50)
        snooper.observe(2.seconds)
      for (_ <- 0 until 50)
        snooper.observe(3.seconds)
      for (_ <- 0 until 1000)
        snooper.observe(8.seconds)
      ctl.advance(12.seconds)
      tmr.tick()
      assert(snooper.handleBytes() == 2000.bytes)
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:62,代码来源:RequestSnooperTest.scala


示例15: ThriftServerFramedCodecTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.thrift

import com.twitter.finagle.Service
import com.twitter.finagle.tracing._
import com.twitter.finagle.util.ByteArrays
import com.twitter.util.Future
import org.apache.thrift.protocol.{TBinaryProtocol, TMessage, TMessageType}
import org.junit.runner.RunWith
import org.mockito.Matchers
import org.mockito.Mockito.when
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ThriftServerFramedCodecTest extends FunSuite with MockitoSugar {
  val protocolFactory = new TBinaryProtocol.Factory()

  test("ThriftServerTracingFilter read header correctly") {
    val traceId = TraceId(Some(SpanId(1L)), None, SpanId(2L), Some(true), Flags().setDebug)
    val bufferingTracer = new BufferingTracer
    Trace.letTracer(bufferingTracer) {
      val filter = new TTwitterServerFilter("service", protocolFactory)
  
      val upgradeMsg = new OutputBuffer(protocolFactory)
      upgradeMsg().writeMessageBegin(new TMessage(ThriftTracing.CanTraceMethodName, TMessageType.CALL, 0))
      val options = new thrift.ConnectionOptions
      options.write(upgradeMsg())
      upgradeMsg().writeMessageEnd()
  
      val service = mock[Service[Array[Byte], Array[Byte]]]
      when(service(Matchers.any[Array[Byte]])).thenReturn(Future(Array[Byte]()))
  
      // now finagle knows we can handle the headers
      filter(upgradeMsg.toArray, service)
  
      // let's create a header
      val header = new thrift.RequestHeader
      header.setSpan_id(2L)
      header.setTrace_id(1L)
      header.setSampled(true)
      header.setFlags(1L)
  
      val ignoreMsg = new OutputBuffer(protocolFactory)
      ignoreMsg().writeMessageBegin(new TMessage("ignoreme", TMessageType.CALL, 0))
      new thrift.ConnectionOptions().write(ignoreMsg())
      ignoreMsg().writeMessageEnd()
  
      filter(ByteArrays.concat(OutputBuffer.messageToArray(header, protocolFactory), ignoreMsg.toArray), service)
  
      bufferingTracer.iterator foreach { record =>
        assert(record.traceId == traceId)
        assert(record.traceId.flags == traceId.flags)
      }
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:58,代码来源:ThriftServerFramedCodecTest.scala


示例16: ClientIdRequiredFilterTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.thrift

import com.twitter.conversions.time._
import com.twitter.finagle.Service
import com.twitter.util.{Await, Future}
import org.junit.runner.RunWith
import org.mockito.Matchers
import org.mockito.Mockito.{times, verify, when}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ClientIdRequiredFilterTest extends FunSuite with MockitoSugar {

  case class ClientIdRequiredFilterContext(underlying: Service[String,String]) {
    lazy val service = new ClientIdRequiredFilter andThen underlying
  }

  val request = "request"
  val response = Future.value("response")
  val clientId = ClientId("test")
  
  test("ClientIdRequiredFilter passes through when ClientId exists") {
    val c = ClientIdRequiredFilterContext(mock[Service[String,String]])
    import c._

    when(underlying(request)).thenReturn(response)
    clientId.asCurrent {
      val result = service(request)
      assert(Await.result(result, 10.seconds) == Await.result(response, 10.seconds))
      result
    }
  }

  test("ClientIdRequiredFilter throws NoClientIdSpecifiedException when ClientId does not exist") {
    val c = ClientIdRequiredFilterContext(mock[Service[String,String]])
    import c._

    ClientId.let(None) {
      intercept[NoClientIdSpecifiedException]{
        Await.result(service(request), 10.seconds)
      }
      verify(underlying, times(0)).apply(Matchers.anyString())
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:48,代码来源:ClientIdRequiredFilterTest.scala


示例17: ChannelBufferTransportTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.thrift.transport.netty3

import org.jboss.netty.buffer.ChannelBuffer
import org.junit.runner.RunWith
import org.mockito.Mockito.{verify, when}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class ChannelBufferTransportTest extends FunSuite with MockitoSugar {

  class ChannelContext{
    val buf = mock[ChannelBuffer]
    lazy val t = new ChannelBufferToTransport(buf)
  }
  val bb = "hello".getBytes

  test("ChannelBufferToTransport writes bytes to the underlying ChannelBuffer") {
    val c = new ChannelContext
    import c._

    t.write(bb, 0, 1)
    verify(buf).writeBytes(bb, 0, 1)

    t.write(bb, 1, 2)
    verify(buf).writeBytes(bb, 1, 2)

    t.write(bb, 0, 5)
    verify(buf).writeBytes(bb, 1, 2)
  }

  test("ChannelBufferToTransport reads bytes from the underlying ChannelBuffer") {
    val c = new ChannelContext
    import c._

    val nReadable = 5
    when(buf.readableBytes).thenReturn(nReadable)
    val b = new Array[Byte](nReadable)
    assert(t.read(b, 0, 10) == nReadable)
    assert(t.read(b, 0, 3) == 3)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:44,代码来源:ChannelBufferTransportTest.scala


示例18: EncoderTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.memcached.protocol.text

import org.jboss.netty.buffer.ChannelBuffer
import org.jboss.netty.channel.{ChannelHandlerContext, Channel}
import org.junit.runner.RunWith
import org.mockito.Mockito.{verify, when}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

import com.twitter.finagle.memcached.util.ChannelBufferUtils.channelBufferToString
import com.twitter.io.Buf

@RunWith(classOf[JUnitRunner])
class EncoderTest extends FunSuite with MockitoSugar {

  test("not alter the tokens it is serializing") {
    val channel = mock[Channel]
    val context = mock[ChannelHandlerContext]
    val addr = mock[java.net.SocketAddress]
    when(context.getChannel) thenReturn channel
    when(channel.getLocalAddress) thenReturn addr
    val encoder = new Encoder

    def encode(x: AnyRef) = {
      val encoded = encoder.encode(context, channel, x)
      Buf.Utf8.unapply(encoded).get
    }

    def encodeIsPure(x: AnyRef) = {
      val buf1 = encode(x)
      val buf2 = encode(x)
      assert(buf1 == buf2)
    }

    info("tokens")
    encodeIsPure(Tokens(Seq(Buf.Utf8("tok"))))

    info("tokens with data")
    encodeIsPure(TokensWithData(Seq(Buf.Utf8("foo")), Buf.Utf8("bar"), None))

    info("tokens with data and cas")
    encodeIsPure(TokensWithData(Seq(Buf.Utf8("foo")), Buf.Utf8("baz"), Some(Buf.Utf8("quux"))))

    info("stat lines")
    encodeIsPure(
      StatLines(
        Seq(
          Tokens(Seq(Buf.Utf8("tok1"))),
          Tokens(Seq(Buf.Utf8("tok2")))
        )
      )
    )

    info("value lines")
    encodeIsPure(
      ValueLines(Seq(TokensWithData(Seq(Buf.Utf8("foo")), Buf.Utf8("bar"), Some(Buf.Utf8("quux")))))
    )
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:61,代码来源:EncoderTest.scala


示例19: ParsingActorSpec

//设置package包名称以及导入依赖的类
package com.mikemunhall.simpletwitterstats.server

import java.util.Date
import akka.actor.Props
import akka.testkit.{TestActorRef, TestProbe}
import com.mikemunhall.simpletwitterstats.server.ParsingActor.Parse
import com.mikemunhall.simpletwitterstats.server.PersistingActor.Persist
import org.mockito.Mockito.when
import twitter4j.{HashtagEntity, Status, URLEntity}

class ParsingActorSpec extends ActorUnitSpec {

  val persistingActorProbe = TestProbe()

  val underTest = TestActorRef(Props(new ParsingActor {
    override val persistingActor = persistingActorProbe.ref
  }))

  "The actor" should "create a Tweet from a Status and delegate to the persisting actor" in {
    val status = mock[Status]
    when(status.getId).thenReturn(12345l)
    when(status.getCreatedAt).thenReturn(new Date())
    when(status.getText).thenReturn("hi")
    when(status.getHashtagEntities).thenReturn(Array[HashtagEntity]())
    when(status.getURLEntities).thenReturn(Array[URLEntity]())

    underTest ! Parse(status)

    val message = persistingActorProbe.expectMsgType[Persist]
    message.tweet.id should be (12345l)
  }
} 
开发者ID:mmunhall,项目名称:simple-twitter-stats,代码行数:33,代码来源:ParsingActorSpec.scala


示例20: GameEditionServiceTest

//设置package包名称以及导入依赖的类
package com.buysomegames.service

import java.time.LocalDate
import java.util.concurrent.TimeUnit

import com.buysomegames.controller.response.GameEditionsResponse
import com.buysomegames.model.{GameEdition, GameEditionGame, Platform}
import com.buysomegames.repository.GameEditionRepository
import org.bson.types.ObjectId
import org.mockito.Mockito.when
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, Matchers, WordSpec}

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

class GameEditionServiceTest extends WordSpec with MockitoSugar with Matchers with BeforeAndAfterEach {
  var gameEditionService: GameEditionService = _
  var mockGameEditionRepository: GameEditionRepository = _

  override protected def beforeEach(): Unit = {
    mockGameEditionRepository = mock[GameEditionRepository]
    gameEditionService = new GameEditionService(gameEditionRepository = mockGameEditionRepository)
  }

  "GameService.handleFindAllGames" should {
    "create GamesResponse from result of GameRepository.findAllGames" in {
      val gameEdition = new GameEdition(
        id = new ObjectId(),
        name = "Uncharted",
        region = "US",
        platform = new Platform(id = "PS3", name = "Playstation 3"),
        game = new GameEditionGame(id = new ObjectId(), name = "Uncharted"),
        releaseDate = LocalDate.parse("2007-11-16")
      )
      when(mockGameEditionRepository.findAllGameEditions).thenReturn(Future.successful(Seq(gameEdition)))
      val responseFuture: Future[GameEditionsResponse] = gameEditionService.handleFindAllGameEditions
      val response = Await.result(responseFuture, Duration.create(10, TimeUnit.SECONDS))
      response.gameEditions should contain only gameEdition
    }
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:43,代码来源:GameEditionServiceTest.scala



注:本文中的org.mockito.Mockito.when类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala macros类代码示例发布时间:2022-05-23
下一篇:
Scala LocalDate类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap