当前位置: 首页>>代码示例>>Scala>>正文


Scala Mockito类代码示例

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


在下文中一共展示了Mockito类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: HttpJsonTopicFetcherTest

//设置package包名称以及导入依赖的类
package com.groupon.dse.kafka.topic

import org.mockito.Mockito
import org.scalatest.{BeforeAndAfter, FlatSpec}

class HttpJsonTopicFetcherTest extends FlatSpec with BeforeAndAfter {

  "The topic fetcher" should "return the correct list of topics " in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val content = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":true}},{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\"}}],\"extras\":\"test\"}"
    Mockito.doReturn(Some(content)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq(TopicAndMetadata("topic1", Map("m1" -> "v1", "m2" -> true.asInstanceOf[AnyRef])), TopicAndMetadata("topic2", Map("m3" -> "v3"))))
  }

  "The topic fetcher" should "return an empty list if the Json in incorrect " in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val content = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":true}}{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\"}}],\"extras\":\"test\"}"
    Mockito.doReturn(Some(content)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq())
  }

  "The topic fetcher " should "return the filtered list if the name field is missing for any topic" in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val contents = "{\"topics\":[{\"name\":\"topic1\",\"metadata\":{\"m1\":\"v1\",\"m2\":\"v2\"}},{\"name1\":\"topic2\",\"enabled\":\"false\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}},{\"name\":\"topic3\",\"enabled\":\"true\",\"metadata\":{\"m3\":\"v3\",\"m4\":\"v4\"}}],\"extras\":\"test\"}"
    Mockito.doReturn(Some(contents)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq(TopicAndMetadata("topic1", Map("m1" -> "v1", "m2" -> "v2")), TopicAndMetadata("topic3", Map("m3" -> "v3", "m4" -> "v4"))))
  }

  "The topic fetcher" should "return an empty map if no metadata is provided" in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    val contents = "{\"topics\":[{\"name\":\"topic1\"},{\"name\":\"topic2\",\"metadata\":{\"m3\":\"v3\",\"m4\":{\"m5\":\"v5\"},\"bool\":true}}]}"
    Mockito.doReturn(Some(contents)).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq(TopicAndMetadata("topic1", Map()), TopicAndMetadata("topic2", Map("m3" -> "v3", "m4" -> Map("m5" -> "v5").asInstanceOf[AnyRef], "bool" -> true.asInstanceOf[AnyRef]))))
  }

  "The topic fetcher" should "return an empty list of topics if there is any problem when fetching the Json" in {
    val http = Mockito.spy(new HttpJsonTopicFetcher("http://test-url"))
    Mockito.doReturn(None).when(http).getContentFromUrl
    assert(http.fetchTopics == Seq.empty)
  }

} 
开发者ID:groupon,项目名称:baryon,代码行数:43,代码来源:HttpJsonTopicFetcherTest.scala

示例3: PrintNInterpreterSpec

//设置package包名称以及导入依赖的类
package interpreter.impl

import org.mockito.Mockito

class PrintNInterpreterSpec extends BaseInterpreterSpec {

  "PrintInterpreter" should "print the given number to the current window" in new Env {
    val ctxSpy = Mockito.spy(ctx)
    run(ctxSpy)("<PRINTN 123>")

    Mockito.verify(ctxSpy).out("123")
  }

  it should "fail for too many arguments" in new Env {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINTN 123 456>")
    }
  }

  it should "fail for too few arguments" in new Env {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINTN>")
    }
  }

  it should "fail for wrong type of arguments" in new Env {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINTN \"Not bloody likely!\">")
    }
  }
} 
开发者ID:falsewasnottrue,项目名称:szilla,代码行数:32,代码来源:PrintNInterpreterSpec.scala

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

示例5: PrintInterpreterSpec

//设置package包名称以及导入依赖的类
package interpreter.impl

import org.mockito.Mockito

class PrintInterpreterSpec extends BaseInterpreterSpec {

  "PrintInterpreter" should "print the given string to the current window" in new Env {
    val ctxSpy = Mockito.spy(ctx)
    run(ctxSpy)("<PRINT \"Not bloody likely!\">")

    Mockito.verify(ctxSpy).out("Not bloody likely!")
  }

  it should "fail for too many arguments" in new Env {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINT \"Not bloody likely!\" 123>")
    }
  }

  it should "fail for too few arguments" in new Env {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINT>")
    }
  }

  it should "fail for wrong type of arguments" in new Env {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINT 123>")
    }
  }
} 
开发者ID:falsewasnottrue,项目名称:szilla,代码行数:32,代码来源:PrintInterpreterSpec.scala

示例6: PrintDInterpreterSpec

//设置package包名称以及导入依赖的类
package interpreter.impl

import models.{Properties, PropertyName}
import org.mockito.Mockito

class PrintDInterpreterSpec extends BaseInterpreterSpec {

  trait Env0 extends Env {
    val lantern = createObject("LANTERN", Properties().add(PropertyName.DESC, "brass lantern"))
    val livingRoom = createRoom("LIVING-ROOM", Properties().add(PropertyName.DESC, "living room"))
  }

  "PrintInterpreter" should "print the DESC of the given object." in new Env0 {
    val ctxSpy = Mockito.spy(ctx)
    run(ctxSpy)("<PRINTD ,LANTERN>")

    Mockito.verify(ctxSpy).out("brass lantern")
  }

  it should "print the DESC of the given room." in new Env0 {
    val ctxSpy = Mockito.spy(ctx)
    run(ctxSpy)("<PRINTD ,LIVING-ROOM>")

    Mockito.verify(ctxSpy).out("living room")
  }

  it should "fail for too many arguments" in new Env0 {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINTD ,LANTERN 123>")
    }
  }

  it should "fail for too few arguments" in new Env0 {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINTD>")
    }
  }

  it should "fail for wrong type of arguments" in new Env0 {
    intercept[IllegalArgumentException] {
      run(ctx)("<PRINTD \"Not bloody likely!\">")
    }
  }
} 
开发者ID:falsewasnottrue,项目名称:szilla,代码行数:45,代码来源:PrintDInterpreterSpec.scala

示例7: TellInterpreterSpec

//设置package包名称以及导入依赖的类
package interpreter.impl

import interpreter.Global
import models._
import org.mockito.Mockito

class TellInterpreterSpec extends BaseInterpreterSpec {

  "TellInterpreter" should "evaluate and print its operands" in new Env {
    Global.define(GlobalVariable("NAME"), StringValue("Anton"))
    val ctxSpy = Mockito.spy(ctx)

    run(ctxSpy)("<TELL \"Hallo \" ,NAME \"!\">")

    Mockito.verify(ctxSpy).out("Hallo ")
    Mockito.verify(ctxSpy).out("Anton")
    Mockito.verify(ctxSpy).out("!")
  }
} 
开发者ID:falsewasnottrue,项目名称:szilla,代码行数:20,代码来源:TellInterpreterSpec.scala

示例8: InfluxServiceTests

//设置package包名称以及导入依赖的类
package com.bwsw.cloudstack.pulse.ut.influx

import com.bwsw.cloudstack.pulse.influx.InfluxService
import org.influxdb.InfluxDB
import org.influxdb.dto._
import org.mockito.Mockito
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import scala.collection.JavaConverters._

class InfluxServiceTests extends FlatSpec with Matchers with BeforeAndAfterAll {

  val username = "username"
  val password = "password"
  val database = "database"
  var queryResult: QueryResult = _

  override def beforeAll(): Unit = {
    val values = List(List("foo".asInstanceOf[AnyRef], "50".asInstanceOf[AnyRef]).asJava).asJava

    val series = new QueryResult.Series
    series.setColumns(List("name", "cpu").asJava)
    series.setName("cpu")
    series.setValues(values)

    val result = new QueryResult.Result
    result.setSeries(List(series).asJava)

    queryResult = new QueryResult
    queryResult.setResults(List(result).asJava)
  }

  it should "Create Influx Connection" in {
    InfluxService.connect("http://localhost:8086", username, password, database)
  }

  it should "Query Influx DB" in {
    val mockInfluxDB = Mockito.mock(classOf[InfluxDB])
    Mockito.when(mockInfluxDB.query(new Query("SELECT * FROM cpu", database))).thenReturn(queryResult)
    InfluxService.influxDB = mockInfluxDB
    InfluxService.dbName = database
    val result = InfluxService.query("SELECT * FROM cpu")
    result.hasError shouldBe false
  }

  override def afterAll(): Unit = {
  }


} 
开发者ID:bwsw,项目名称:cs-pulse-server,代码行数:51,代码来源:InfluxServiceTests.scala

示例9: any

//设置package包名称以及导入依赖的类
package ru.finagram.test

import org.mockito.verification.VerificationWithTimeout
import org.mockito.{ ArgumentCaptor, Mockito }

import scala.concurrent.duration._
import scala.reflect.Manifest

trait MockitoSugar extends org.scalatest.mockito.MockitoSugar {

  def any[T <: Any](implicit manifest: Manifest[T]): T = {
    org.mockito.Matchers.any(manifest.runtimeClass.asInstanceOf[Class[T]])
  }

  def argumentCaptor[T <: Any](implicit manifest: Manifest[T]): ArgumentCaptor[T] = {
    ArgumentCaptor.forClass(manifest.runtimeClass.asInstanceOf[Class[T]])
  }

  def timeout(duration: Duration): VerificationWithTimeout = {
    Mockito.timeout(duration.toMillis.toInt)
  }
} 
开发者ID:finagram,项目名称:finagram,代码行数:23,代码来源:MockitoSugar.scala

示例10: StackDescribeTest

//设置package包名称以及导入依赖的类
package uk.co.telegraph.plugin.pipeline.tasks

import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.{eq => mEq}
import org.mockito.Mockito
import org.mockito.Mockito.{times, verify}
import org.scalatest.junit.JUnitRunner
import org.scalatest.{BeforeAndAfter, FunSpec, Matchers}
import sbt.Logger
import uk.co.telegraph.cloud._
import uk.co.telegraph.plugin.pipeline.StackAuth
import StackDescribeTest._

@RunWith(classOf[JUnitRunner])
class StackDescribeTest extends FunSpec with BeforeAndAfter with Matchers{

  val SampleInvalidStackName = "invalid-test-stack"

  before{
    Mockito.reset(MockInterpreter)
  }

  describe("Given the 'StackDescribe' operation, "){
    it("I should be able to get a stack name if the stack exists"){
      Mockito.when(MockInterpreter.apply( mEq(Describe(SampleStackName)) ))
        .thenReturn(Some(SampleStackInfo))

      val res = StackDescribeMocked(
        SampleStackName,
        SampleStackRegion,
        SampleStackAuth
      )(SampleEnvironment, SampleLogger)

      res shouldBe Some(SampleStackInfo)

      verify(MockInterpreter, times(1)).apply( mEq(Describe(SampleStackName)) )
    }

    it("I should get nothing with an invalid stack"){
      Mockito.when(MockInterpreter.apply( mEq(Describe(SampleInvalidStackName)) ))
        .thenReturn(None)

      val res = StackDescribeMocked(
        SampleInvalidStackName,
        SampleStackRegion,
        SampleStackAuth
      )(SampleEnvironment, SampleLogger)

      res shouldBe None

      verify(MockInterpreter, times(1)).apply( mEq(Describe(SampleInvalidStackName)) )
    }
  }
}

object StackDescribeTest {
  object StackDescribeMocked extends StackDescribe{
    override def interpreter(region: StackRegion, auth: StackAuth)(implicit logger: Logger) = MockInterpreter
  }
} 
开发者ID:telegraph,项目名称:sbt-pipeline-plugin,代码行数:61,代码来源:StackDescribeTest.scala

示例11: GameServiceTest

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

import java.util.concurrent.TimeUnit

import com.buysomegames.controller.response.GamesResponse
import com.buysomegames.model.Game
import com.buysomegames.repository.GameRepository
import org.mockito.Mockito
import org.scalatest.Matchers._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, WordSpec}

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

class GameServiceTest extends WordSpec with MockitoSugar with BeforeAndAfterEach {
  var gameService: GameService = _
  var mockGameRepository: GameRepository = _

  override protected def beforeEach(): Unit = {
    mockGameRepository = mock[GameRepository]
    gameService = new GameService(gameRepository = mockGameRepository)
  }

  "GameService.handleFindAllGames" should {
    "create GamesResponse from result of GameRepository.findAllGames" in {
      val pokemonRed = new Game(name = "Pokemon Red", description = "Boring :(")
      Mockito.when(mockGameRepository.findAllGames).thenReturn(Future.successful(Seq(pokemonRed)))
      val responseFuture: Future[GamesResponse] = gameService.handleFindAllGames
      val response = Await.result(responseFuture, Duration.create(10, TimeUnit.SECONDS))
      response.games should contain only pokemonRed
    }
  }
} 
开发者ID:kaliy,项目名称:buysomegames,代码行数:35,代码来源:GameServiceTest.scala

示例12: ProjectDataGathererImplTest

//设置package包名称以及导入依赖的类
package com.github.tweets.data

import com.github.tweets.common.{ProjectData, TweetInfo, GitHubProjectInfo}
import com.github.tweets.gateway.{TwitterAPIGateway, GitHubAPIGateway}
import org.mockito.Mockito
import org.scalatest.FunSuite
import org.scalatest.mock.MockitoSugar

class ProjectDataGathererImplTest extends FunSuite with MockitoSugar {
  val gitHubAPIGateway = mock[GitHubAPIGateway]
  val twitterAPIGateway = mock[TwitterAPIGateway]

  val project1 = mock[GitHubProjectInfo]
  val project2 = mock[GitHubProjectInfo]
  val githubProjects = List(project1, project2)

  val tweet1 = mock[TweetInfo]
  val tweet2 = mock[TweetInfo]
  val tweet3 = mock[TweetInfo]

  val tweetsForProject1 = List(tweet1, tweet2)
  val tweetsForProject2 = List(tweet3)

  val dataGatherer = new ProjectDataGathererImpl(gitHubAPIGateway, twitterAPIGateway)

  test("should gather project data for 'random' keyword") {
    Mockito.when(gitHubAPIGateway.fetchTopProjects("random")).thenReturn(List(project1, project2))
    Mockito.when(twitterAPIGateway.fetchTweets(project1)).thenReturn(tweetsForProject1)
    Mockito.when(twitterAPIGateway.fetchTweets(project2)).thenReturn(tweetsForProject2)

    val result = dataGatherer.gatherProjectData("random")

    assert(result === List(ProjectData(project1, tweetsForProject1), ProjectData(project2, tweetsForProject2)))
  }
} 
开发者ID:andrei-l,项目名称:tweets-for-github-projects-gatherer,代码行数:36,代码来源:ProjectDataGathererImplTest.scala

示例13: LoopClockTest

//设置package包名称以及导入依赖的类
package hcube.scheduler

import hcube.scheduler.utils.TimeUtil.SleepFn
import org.mockito.{ArgumentCaptor, Mockito}
import org.specs2.mock.{Mockito => MockitoSpecs2}
import org.specs2.mutable.Specification

import scala.collection.JavaConversions._
import scala.collection.mutable
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext}

class LoopClockTest extends Specification with MockitoSpecs2 {

  implicit val ec: ExecutionContext = ExecutionContext.Implicits.global


  "generate expected tick intervals" >> {
    val tickReceiver = mock[TickReceiver]
    val timeQueue = mutable.Queue(1000L, 1300L, 2040L, 3020L, 4200L, 7200L, 8000L)
    val timeFn = () => {
      timeQueue.dequeue()
    }
    val sleep = mock[SleepFn]

    val clock = new LoopClock(
      tickReceiver,
      tickPeriod = 1000,
      tolerance = 50,
      continueOnInterrupt = false,
      currentTimeMillis = timeFn,
      sleep = sleep,
      stopTime = Some(8000)
    )

    Await.result(clock(), Duration.Inf)

    val t0Arg = ArgumentCaptor.forClass(classOf[Long])
    val t1Arg = ArgumentCaptor.forClass(classOf[Long])
    Mockito.verify(tickReceiver, Mockito.times(6))
      .tick(t0Arg.capture(), t1Arg.capture())

    val sleepArg = ArgumentCaptor.forClass(classOf[Long])
    Mockito.verify(sleep, Mockito.times(4))
      .apply(sleepArg.capture())

    List(1000L, 2000L, 3000L, 4000L, 5000L, 6000L) must_== t0Arg.getAllValues.toList
    List(2000L, 3000L, 4000L, 5000L, 6000L, 8000L) must_== t1Arg.getAllValues.toList

    List(700, 960, 980, 800L) must_== sleepArg.getAllValues.toList
  }

} 
开发者ID:hcube-dev,项目名称:hcube-scheduler,代码行数:54,代码来源:LoopClockTest.scala


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