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

Scala MockFactory类代码示例

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

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



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

示例1: StuffTest

//设置package包名称以及导入依赖的类
import org.scalamock.scalatest.MockFactory
import org.scalatest.FlatSpec

class StuffTest extends FlatSpec with MockFactory {

  "A stuff" should "write stuff to db" in {
    val dbmock = mock[Database]
    Stuff.setDatabase(dbmock)
    (dbmock.write _).expects("A", "string").once()
    (dbmock.close _).expects().once()
    Stuff.writeAtoDB()
  }

  "A stuff" should "write B stuff to db" in {
    val dbmock = mock[Database]
    Stuff.setDatabase(dbmock)
    (dbmock.write _).expects("B", "string").twice()
    (dbmock.close _).expects().twice()
    Stuff.writeBtoDB()
  }
} 
开发者ID:mrcarlosrendon,项目名称:scala-unit-testing,代码行数:22,代码来源:StuffTest.scala


示例2: MockClient

//设置package包名称以及导入依赖的类
package featherbed

import java.net.URL

import com.twitter.finagle.{Filter, Http}
import com.twitter.finagle.http.{Request, Response}
import org.scalamock.matchers.Matcher
import org.scalamock.scalatest.MockFactory

package object fixture {
  private[fixture] class MockClient (
    baseUrl: URL,
    filter: Filter[Request, Response, Request, Response]
  ) extends Client(baseUrl) {
    override def clientTransform(c: Http.Client) = c.filtered(filter)
  }

  trait ClientTest { self: MockFactory =>
    class TransportRequestMatcher(f: Request => Unit) extends Matcher[Any] {
      override def canEqual(x: Any) = x match {
        case x: Request => true
        case _ => false
      }
      override def safeEquals(that: Any): Boolean = that match {
        case x: Request => f(x); true
        case _ => false
      }
    }

    def request(f: Request => Unit): TransportRequestMatcher = new TransportRequestMatcher(f)

    def mockClient(url: String, filter: Filter[Request, Response, Request, Response]): Client =
      new MockClient(new URL(url), filter)
  }
} 
开发者ID:finagle,项目名称:featherbed,代码行数:36,代码来源:package.scala


示例3: EchoBotSpec

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.{MessageReplier, SignatureVerifier}
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}

import scala.concurrent.Future

class EchoBotSpec
  extends FlatSpec
    with Matchers
    with ScalatestRouteTest
    with EventsJsonSupport
    with MockFactory {

  def createBot(
                 sv: SignatureVerifier = mock[SignatureVerifier],
                 mr: MessageReplier = mock[MessageReplier]
               ): EchoLineBot = new EchoLineBot(
    channelSecret = "channelSecret",
    signatureVerifier = sv,
    messageReplier = mr
  )

  it should "reply text message as reveived" in {
    val signatureVerifier = stub[SignatureVerifier]
    (signatureVerifier.isValid _).when(*, *, *) returns true
    val messageReplier = stub[MessageReplier]
    (messageReplier.replyMessage _).when(*, *).returns(Future.successful(Unit))

    val bot = createBot(
      signatureVerifier,
      messageReplier
    )
    val event = MessageEvent(
      replyToken = "replyToken",
      timestamp = 0,
      source = UserSource(id = "1"),
      message = TextMessage(id = "2", text = "test message")
    )
    val body = Events(List(event))
    val header = RawHeader("X-Line-Signature", "signature")

    Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
      status shouldBe StatusCodes.OK
      responseAs[String] shouldBe "OK"
    }
    (signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
    (messageReplier.replyMessage _).verify("replyToken", "test message").once
  }

} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:58,代码来源:EchoBotSpec.scala


示例4: BaseLineBotSpec

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.testkit.ScalatestRouteTest
import bot.line.client.SignatureVerifier
import bot.line.json.EventsJsonSupport
import bot.line.model.event._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, _}

class BaseLineBotSpec
  extends FlatSpec
    with Matchers
    with ScalatestRouteTest
    with EventsJsonSupport
    with MockFactory {

  def createBot(
                 sv: SignatureVerifier = mock[SignatureVerifier],
                 rv:List[Event] => Unit
               ): BaseLineBot[Unit] = new BaseLineBot[Unit] {
    override val channelSecret: String = "channelSecret"
    override val signatureVerifier: SignatureVerifier = sv

    override def receive(events: List[Event]): Unit = rv(events)
  }

  it should "Verify signature" in {
    val signatureVerifier = stub[SignatureVerifier]
    (signatureVerifier.isValid _).when(*, *, *) returns true
    val receive = stubFunction[List[Event], Unit]
    receive.when(*).returns(Unit)
    val bot = createBot(
      signatureVerifier,
      receive
    )
    val event = MessageEvent(
      replyToken = "replyToken",
      timestamp = 0,
      source = UserSource(id = "1"),
      message = TextMessage(id = "2", text = "test message")
    )
    val body = Events(List(event))
    val header = RawHeader("X-Line-Signature", "signature")

    Post("/line/callback", body).withHeaders(header) ~> bot.routes ~> check {
      status shouldBe StatusCodes.OK
      responseAs[String] shouldBe "OK"
    }
    (signatureVerifier.isValid _).verify("channelSecret", *, "signature").once
    receive.verify(body.events).once
  }

} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:56,代码来源:BaseLineBotSpec.scala


示例5: NegociosFunctionalTest

//设置package包名称以及导入依赖的类
package controllers

import org.scalamock.scalatest.MockFactory
import org.scalatest._
import org.scalatest.concurrent.IntegrationPatience
import org.scalatestplus.play._
import play.api.mvc.Results


class NegociosFunctionalTest extends FlatSpec with Matchers with OptionValues
with WsScalaTestClient with BeforeAndAfterEach with BeforeAndAfterAll with Results
with MockFactory with OneServerPerSuite with HtmlUnitFactory with AllBrowsersPerSuite with IntegrationPatience {

  override lazy val browsers = Vector(
    ChromeInfo,
    FirefoxInfo(firefoxProfile),
    InternetExplorerInfo
  )

  override def afterAll(): Unit = {
  }

  val host = s"http://localhost:$port"

  def sharedTests(browser: BrowserInfo) = {

    "Index" should s"mostrar los negocios en el listado y cargar la configuracion ${browser.name}" in {
      go to s"$host/"
      pageTitle shouldBe "Hello MV - Configurador"
      click on find(name("configuracion")).value

      eventually(currentUrl shouldBe s"$host/negocios/avanza_seguro/configuracion")
    }

    it should s"cargar un negocio ${browser.name}" in {
      go to s"$host/"
      pageTitle shouldBe "Hello MV - Configurador"
      click on find(name("negocios")).value

      eventually(currentUrl shouldBe s"$host/negocios/avanza_seguro")
    }

  }

  override def convertToLegacyEqualizer[T](left: T): LegacyEqualizer[T] = ???

  override def convertToLegacyCheckingEqualizer[T](left: T): LegacyCheckingEqualizer[T] = ???
} 
开发者ID:luissalda1995,项目名称:generador-vistas,代码行数:49,代码来源:NegociosFunctionalTest.scala


示例6: LircParserSpec

//设置package包名称以及导入依赖的类
package services

import javax.inject.Provider

import io.TestableProcessLogger
import org.scalatest.{FlatSpec, MustMatchers}
import org.scalamock.scalatest.MockFactory

import scala.sys.process._


class LircParserSpec extends FlatSpec with MustMatchers with MockFactory {

  "The irsend command" should "find devices" in {

    val process = mock[ProcessCreation]
    val builder = mock[ProcessBuilder]
    val provider = mock[Provider[TestableProcessLogger]]
    val logger = mock[TestableProcessLogger]

    (process.apply(_:String,_:Seq[String])).expects("irsend", Seq("list", "", "")).returns(builder)
    (logger.processLogger _).expects().returns(null)
    (logger.lines _).expects().returns(List("irsend: sony", "irsend: jvc"))
    (provider.get _).expects().returns(logger)
    (builder.lineStream_! (_: ProcessLogger)).expects(*)

    val lircParser = new DefaultLircParser(process, provider)
    lircParser.listDevices must be(Seq("sony", "jvc"))
  }

  it should "find buttons for a device" in {

    val process = mock[ProcessCreation]
    val builder = mock[ProcessBuilder]
    val provider = mock[Provider[TestableProcessLogger]]
    val logger = mock[TestableProcessLogger]

    (process.apply(_:String,_:Seq[String])).expects("irsend", Seq("list", "sony", "")).returns(builder)
    (logger.processLogger _).expects().returns(null)
    (logger.lines _).expects().returns(List("irsend: 0000000000000481 KEY_VOLUMEUP", "irsend: 0000000000000c81 KEY_VOLUMEDOWN"))
    (provider.get _).expects().returns(logger)
    (builder.lineStream_! (_:ProcessLogger)).expects(*)

    val lircParser = new DefaultLircParser(process, provider)
    lircParser.listButtons("sony") must be(Seq("KEY_VOLUMEUP", "KEY_VOLUMEDOWN"))
  }

  it should "press buttons for a device" in {

    val process = mock[ProcessCreation]
    val builder = mock[ProcessBuilder]
    val provider = mock[Provider[TestableProcessLogger]]
    val logger = mock[TestableProcessLogger]

    (process.apply(_:String,_:Seq[String])).expects("irsend", Seq("SEND_ONCE", "sony", "KEY_VOLUMEUP")).returns(builder)
    (builder.! _).expects().returns(0)

    val lircParser = new DefaultLircParser(process, null)
    lircParser.pressButton("sony", "KEY_VOLUMEUP") must be(true)
  }
} 
开发者ID:jimnybob,项目名称:smartii-ir,代码行数:62,代码来源:LircParserSpec.scala


示例7: SARSASpec

//设置package包名称以及导入依赖的类
import org.scalatest._

import org.scalamock.scalatest.MockFactory

import scarla.algorithm.SARSA
import scarla.mapping.Mapping
import scarla.policy.Greedy
import scarla.domain.State

class SARSASpec extends FlatSpec with Matchers with MockFactory {

  "The SARSA algorithm" should "use the on-policy future value" in {
    val m = mock[Mapping]
    val p = new Greedy(m)
    val s = State(Vector(0), Vector(0, 1), false)

    (m.Q(_: State)).expects(s).returning(Vector(2.0, -1.0))
    (m.Q(_: State, _: Int)).expects(s, 0).returning(2.0)

    val t = SARSA.target(s, m, p)
    t should be (2.0)
  }
} 
开发者ID:tspooner,项目名称:scaRLa,代码行数:24,代码来源:SARSA.scala


示例8: ImplicitsUserRetrievalTest

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

import com.tomogle.dependencyinjection.Implicits.UserRetrieval
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class ImplicitsUserRetrievalTest extends FlatSpec with Matchers with MockFactory {

  behavior of "getting a user"

  trait UserRetrievalFixture extends UserRetrieval {
    val id = 567L
    val user = User(id, "a user")
  }

  trait UserRetrievalFixtureMockRepository extends UserRetrievalFixture {
    implicit val userRepository = mock[UserRepository]
  }

  trait UserRetrievalFixtureStubRepository extends UserRetrievalFixture {
    implicit val userRepository = stub[UserRepository]
  }

    it should "ask for the user from the repository" in new UserRetrievalFixtureMockRepository {
    (userRepository get _) expects id
    getUser(id)
  }

  it should  "return the user returned from the repository" in new UserRetrievalFixtureStubRepository {
    (userRepository get _) when * returns user
    val actualUserResult = getUser(id)
    actualUserResult should equal(user)
  }

} 
开发者ID:tom-ogle,项目名称:scala-dependency-injection,代码行数:36,代码来源:ImplicitsUserRetrievalTest.scala


示例9: CakeUserRetrievalTest

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

import com.tomogle.dependencyinjection.Cake.{HardCodedUserRetrievalComponent, UserRepositoryComponent, UserRetrievalComponent}
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class CakeUserRetrievalTest extends FlatSpec with Matchers with MockFactory {

  behavior of "getting a user from HardCodedUserRetrieval"

  trait HardCodedUserRetrievalComponentFixture extends HardCodedUserRetrievalComponent {
    val id = 1L
  }

  it should "Return the hard-coded user" in new HardCodedUserRetrievalComponentFixture {

    val expectedUser = User(id, "hard-coded-user")
    val actualUser = userRetrieval.getUser(id)
    actualUser should equal(expectedUser)
  }

  behavior of "getting a user from UserRetrievalComponent"

  trait UserRetrievalComponentFixture extends UserRetrievalComponent with UserRepositoryComponent {
    val id = 1L
    override val userRepository = mock[CakeUserRepository]
  }

  it must "get the user from the repository dependency" in new UserRetrievalComponentFixture {
    userRepository.get _ expects id returning User(id, "user result")
    userRetrieval.getUser(id)
  }
} 
开发者ID:tom-ogle,项目名称:scala-dependency-injection,代码行数:34,代码来源:CakeUserRetrievalTest.scala


示例10: FunctionalInjectionUserRetrievalTest

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

import com.tomogle.dependencyinjection.FunctionalInjection.UserRetrieval
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class FunctionalInjectionUserRetrievalTest extends FlatSpec with Matchers with MockFactory {

  behavior of "getting a user"

  trait UserRetrievalFixture extends UserRetrieval {
    val id = 123L
    val user = User(id, "my user")
    val userRepositoryMock = mock[UserRepository]
    val userRepositoryStub = stub[UserRepository]
  }

  it should "ask for the user from the repository" in new UserRetrievalFixture {
    (userRepositoryMock get _) expects id
    getUser(id)(userRepositoryMock)
  }

  it should "return the user returned from the repository" in new UserRetrievalFixture {
    (userRepositoryStub get _) when * returns user
    val actualUserResult = getUser(id)(userRepositoryStub)
    actualUserResult should equal(user)
  }

} 
开发者ID:tom-ogle,项目名称:scala-dependency-injection,代码行数:30,代码来源:FunctionalInjectionUserRetrievalTest.scala


示例11: ReaderMonadUserRetrievalTest

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

import com.tomogle.dependencyinjection.ReaderMonad.UserRetrieval
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}

class ReaderMonadUserRetrievalTest extends FlatSpec with Matchers with MockFactory {

  behavior of "getting a user"

  trait UserRetrievalFixture extends UserRetrieval {
    val id = 987L
    val user = User(id, "a user")
    val userRepositoryMock = mock[UserRepository]
    val userRepositoryStub = stub[UserRepository]
  }

  it should "ask for the user from the repository" in new UserRetrievalFixture {
    (userRepositoryMock get _) expects id
    getUser(id)(userRepositoryMock)
  }

  it should "return the user retrieved from the repository" in new UserRetrievalFixture {
    (userRepositoryStub get _) when * returns user
    val actualUserResult = getUser(id)(userRepositoryStub)
    actualUserResult should equal(user)
  }


} 
开发者ID:tom-ogle,项目名称:scala-dependency-injection,代码行数:31,代码来源:ReaderMonadUserRetrievalTest.scala


示例12: CheckersControllerSpecGame

//设置package包名称以及导入依赖的类
package de.htwg.se.checkers.controller

import de.htwg.se.checkers.controller.command.{GameStatus, SetPiece}
import de.htwg.se.checkers.model.enumeration.Colour
import org.scalamock.scalatest.MockFactory
import org.scalatest._

class CheckersControllerSpecGame extends WordSpec with Matchers with MockFactory {
  val playerOne = Colour.BLACK
  val playerTwo = Colour.WHITE

  "A new Controller with CheckersTestConfiguration injection" should {
    val ctr = new CheckersController()(CheckersTestConfiguration)
    ctr.movePiece((1, 2), (0, 3))
    ctr.movePiece((0, 5), (1, 4))
    val status = ctr.movePiece((3, 2), (2, 3))

    "get possible moves should contain 1 element" in {
      status should be(true)
      ctr.getPossibleMoves.length should be(1)
    }

    "get possible moves should contain (1,4),(3,2" in {
      ctr.getPossibleMoves should contain((1, 4), (3, 2))
    }
    "get possible pieces" in {
      ctr.getPossiblePieces should contain((1, 4))
    }

    "get possible targets for (0,5)" in {
      ctr.getPossibleTargets((1, 4)) should contain((3, 2))
    }
  }

  "capture piece" should {
    val ctr = new CheckersController()(CheckersTestConfiguration)
    ctr.movePiece((1, 2), (0, 3))
    ctr.movePiece((0, 5), (1, 4))
    ctr.movePiece((3, 2), (2, 3))
    var status = ctr.movePiece((1, 4), (3, 2))

    "get possible moves should contain 1 element" in {
      status should be(true)
    }

    "get no targets" in {
      ctr.getPossibleTargets((1, 0)).length should be(0)
    }

    "hande command" in {
      
      ctr.handleCommand(SetPiece((1, 0), (1, 0)))
      ctr.handleCommand(GameStatus())
    }
  }

} 
开发者ID:T1m1,项目名称:htwg-scala-checkers,代码行数:58,代码来源:CheckersControllerSpecGame.scala


示例13: CheckersControllerSpec

//设置package包名称以及导入依赖的类
package de.htwg.se.checkers.controller

import de.htwg.se.checkers.model.enumeration.Colour
import org.scalamock.scalatest.MockFactory
import org.scalatest._

class CheckersControllerSpec extends WordSpec with Matchers with MockFactory {

  "A new Controller with CheckersTestConfiguration injection" should {
    val ctr = new CheckersController()(CheckersTestConfiguration)

    "have 3 playable rows" in {
      ctr.rows should be(3)
    }
    "have a size of 8" in {
      ctr.size should be(8)
    }
    "the first player should be BLACK" in {
      ctr.playerOne should be(Colour.BLACK)
    }
    "the second player should be WHITE" in {
      ctr.playerTwo should be(Colour.WHITE)
    }

    "In the initial game state" should {
      val currentGameState = ctr.getState

      "player one should come first" in {
        currentGameState.currentPlayer should be(Colour.BLACK)
      }
      "piece at (0,1) should be Black" in {
        currentGameState.field.board(0)(1).get.colour should be(Colour.WHITE)
      }
    }
  }
} 
开发者ID:T1m1,项目名称:htwg-scala-checkers,代码行数:37,代码来源:CheckersControllerSpec.scala


示例14:

//设置package包名称以及导入依赖的类
package io.toolsplus.atlassian.connect.play

import io.toolsplus.atlassian.connect.play.generators.http.HttpGen
import io.toolsplus.atlassian.connect.play.generators.{
  AtlassianConnectJwtGen,
  AtlassianHostGen,
  LifecycleEventGen,
  PlayRequestGen
}
import org.scalamock.scalatest.MockFactory
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatestplus.play.PlaySpec
import play.api.test.{DefaultAwaitTimeout, FutureAwaits}

trait TestSpec
    extends PlaySpec
    with MockFactory
    with GeneratorDrivenPropertyChecks
    with FutureAwaits
    with DefaultAwaitTimeout
    with HttpGen
    with LifecycleEventGen
    with AtlassianHostGen
    with AtlassianConnectJwtGen
    with PlayRequestGen 
开发者ID:toolsplus,项目名称:atlassian-connect-play,代码行数:26,代码来源:TestSpec.scala


示例15: MessageBrokerMessageDispatcherUTest

//设置package包名称以及导入依赖的类
package plumbing

import akka.actor.ActorSystem
import akka.testkit.TestKit
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpecLike, ShouldMatchers, Suite, BeforeAndAfterAll}

class MessageBrokerMessageDispatcherUTest
 extends TestKit(ActorSystem("TestSystem"))
  with FlatSpecLike
  with ShouldMatchers
  with StopSystemAfterAll
  with MockFactory {
  
}

trait StopSystemAfterAll extends BeforeAndAfterAll {

  this: TestKit with Suite =>

  override protected def afterAll(): Unit = {
    super.afterAll()
    system.terminate()
  }

} 
开发者ID:shafiquejamal,项目名称:microservice-template-play,代码行数:27,代码来源:MessageBrokerMessageDispatcherUTest.scala


示例16: AutoCloseableExtensionsTest

//设置package包名称以及导入依赖的类
package net.dericbourg.daily.utils.scala.lib

import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, WordSpec}

import scala.util.{Failure, Try}

class AutoCloseableExtensionsTest extends WordSpec with MockFactory with Matchers {

  "use" should {
    "run block and close resource" in {

      import AutoCloseableExtensions.use

      val innerBlock = mock[Runnable]
      (innerBlock.run _).expects().once()
      val resource = mock[AutoCloseable]
      (resource.close _).expects().once()


      use(resource) { a: AutoCloseable =>
        a should not be null

        innerBlock.run()
      }

    }

    "close resource even after an exception occurred" in {
      import AutoCloseableExtensions.use

      val resource = mock[AutoCloseable]
      (resource.close _).expects().once()

      val tryResult = Try {
        use(resource) { _ =>
          throw new RuntimeException("Expected")
        }
      }

      tryResult match {
        case Failure(e) => e.getMessage shouldEqual "Expected"
        case _ => fail("Unexpected behavior")
      }
    }

    "not fail if resource was null" in {
      import AutoCloseableExtensions.use

      val resource: AutoCloseable = null
      use(resource) { r =>
        r should be(null)
      }
    }
  }
} 
开发者ID:adericbourg,项目名称:daily-utils,代码行数:57,代码来源:AutoCloseableExtensionsTest.scala


示例17: CovarianceCallTest

//设置package包名称以及导入依赖的类
package org.openalgo.analytics

import org.scalamock.scalatest.MockFactory
import org.scalatest.{BeforeAndAfterEach, FunSuite}

import scala.collection.JavaConverters._
import scala.collection.mutable

class CovarianceCallTest extends FunSuite with BeforeAndAfterEach with MockFactory {
  val list1: mutable.Buffer[java.lang.Double] = mutable.Buffer()
  val list2: mutable.Buffer[java.lang.Double] = mutable.Buffer()


  override def beforeEach() {
    list1 += new java.lang.Double(1)
    list1 += new java.lang.Double(2)
    list1 += new java.lang.Double(3)
    list2 += new java.lang.Double(-1)
    list2 += new java.lang.Double(-2)
    list2 += new java.lang.Double(-3)
  }

  override def afterEach() {

  }

  test("testGetCovariance") {
    assert(CovarianceCall.getCovariance(list1.asJava, list1.asJava).round == 1)
    assert(CovarianceCall.getCovariance(list1.asJava, list2.asJava).round == -1)
  }

} 
开发者ID:openalgo,项目名称:analytics,代码行数:33,代码来源:CovarianceCallTest.scala


示例18: WateringListenerTest

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

import java.time.{Clock, Instant}

import akka.actor.{ActorSystem, Props}
import akka.testkit.TestActorRef
import com.softwaremill.macwire.wire
import model.sensor._
import model.sensor.impl.{LocationRepositorySql, LocationSql, SensorRepositorySql}
import mqtt.MqttListenerMessage.ConsumeMessage
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, WordSpec}


class WateringListenerTest extends WordSpec with Matchers with MockFactory {
  "WateringListener" when {

    implicit val system = ActorSystem()
    val clock = mock[Clock]
    val instant = Instant.ofEpochSecond(22)
    (clock.instant _).expects().returning(instant).atLeastOnce()

    "receives the message" should {
      "store it in dao if the message is correct" in {
        val locationRepository = mock[LocationRepositorySql]
        val sensorRepository = mock[SensorRepositorySqlWithCtor]
        val listener = TestActorRef[WateringListener](Props(wire[WateringListener]))
        val sensor = mock[Sensor]
        val humidityPhenomenon = mock[MeasuredPhenomenon]
        val wateringPhenomenon = mock[MeasuredPhenomenon]
        val location = LocationSql("watering-ibiscus", "label")

        (locationRepository.findOrCreateLocation _).expects("watering-ibiscus").returning(location)
        (sensorRepository.findOrCreateSensor _).expects(location, "watering").returning(sensor)

        (sensor.findOrCreatePhenomenon _).expects( "humidity", "", IdentityMeasurementAggregationStrategy).returning(humidityPhenomenon)
        (sensor.addMeasurement _).expects(Measurement(86, Instant.ofEpochSecond(22)), humidityPhenomenon)

        (sensor.findOrCreatePhenomenon _).expects( "watering", "", BooleanMeasurementAggregationStrategy).returning(wateringPhenomenon)
        (sensor.addMeasurement _).expects(Measurement(10, Instant.ofEpochSecond(22)), wateringPhenomenon)

        val correctJson = """ {"ts":8119,"tm":{"hu":{"a":86,"bl":512,"md":1000,"bs":10,"pd":30},"wa":{"ip":true,"wp":20000,"wt":5000},"wlh":true}}"""
        listener ! ConsumeMessage("home/watering/ibisek/telemetry", correctJson)
      }
    }
  }

  class SensorRepositorySqlWithCtor extends SensorRepositorySql(null, null)
} 
开发者ID:vavravl1,项目名称:home_center,代码行数:50,代码来源:WateringListenerTest.scala


示例19: WateringCommanderTest

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

import java.time.Instant

import mqtt.JsonSender
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, WordSpec}
import play.api.libs.json.Writes

class WateringCommanderTest extends WordSpec with Matchers with MockFactory {
  "WateringCommander" when {
    val jsonSender = mock[JsonSender]
    val wateringCommander = new WateringCommander(jsonSender)

    "sends generic command" should {
      "correctly process setting actual time" in {
        val wc = WateringCommand(Set(
          TimeCommand(Instant.ofEpochSecond(42))
        ))
        (jsonSender.send[WateringCommand](_:String, _:WateringCommand)(_:Writes[WateringCommand])).expects("home/watering/ibisek/commands", wc, WateringCommand.comWrites)

        wateringCommander.sendCommand(wc)
      }
    }
  }
} 
开发者ID:vavravl1,项目名称:home_center,代码行数:27,代码来源:WateringCommanderTest.scala


示例20: TeamTest

//设置package包名称以及导入依赖的类
package com.stulsoft.scalamock.examples.simple

import org.scalamock.scalatest.MockFactory
import org.scalatest.{FlatSpec, Matchers}


class TeamTest extends FlatSpec with MockFactory with Matchers {

  behavior of "Team"

  "teamSize" should "return size of team" in {
    // Usage of stub (Record-then-Verify)
    val fakedDbManager = stub[DbManager]
    (fakedDbManager.getTeam _).when("team1").returns(Some(Team("team1", Seq(Person("david", 10), Person("dan", 11)))))
    val person = fakedDbManager.getTeam("team1").get
    person.teamSize should equal(2)
  }
} 
开发者ID:ysden123,项目名称:poc,代码行数:19,代码来源:TeamTest.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Semaphore类代码示例发布时间:2022-05-23
下一篇:
Scala Logging类代码示例发布时间: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