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


Scala OneInstancePerTest类代码示例

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


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

示例1: RulesSpec

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

import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.ai._
import org.scalatest.prop.PropertyChecks

@RunWith(classOf[JUnitRunner])
class RulesSpec extends FlatSpec with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter
    with PropertyChecks with HanabiDomain {
  import SimpleRules._
  import Cards._

  "simple rules" should "have proper number of cards" in {
    forAll { c: Card =>
      whenever(c.level == 1) {
        count(c) shouldBe 3
      }
    }
    forAll { c: Card =>
      whenever(c.level == 5) {
        count(c) shouldBe 1
      }
    }
    forAll { c: Card =>
      whenever(c.level > 1 && c.level < 5) {
        count(c) shouldBe 2
      }
    }
  }

  implicit override val generatorDrivenConfig = PropertyCheckConfiguration(
    minSuccessful = 100,
    maxDiscardedFactor = 15)
} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:43,代码来源:RulesSpec.scala

示例2: PlayerSpec

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

import state._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.ai._

@RunWith(classOf[JUnitRunner])
class PlayerSpec extends FlatSpec with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter {
  import SimpleRules._

  val player = new Player {
    def nextMove(s: GameState) = ???
  }

  val onesToThrees = allCards.filter(_.level < 4)
  val foursFives = allCards.filter(_.level >= 4)
  val (fives, allExceptFives) = allCards.partition(_.level == 5)

  "a player" should "guess its possible cards with no clues" in {
    val possible = player.possibleCards(allExceptFives, 5)
    for (p <- 0 to 4)
      possible(p) should contain theSameElementsAs fives
  }

  it should "guess its possible cards with a single clue" in {
    val possible = player.possibleCards(onesToThrees, 5, Seq(LevelClue(level = 5, position = 3)))
    possible(1) should contain theSameElementsAs allCards.filter(_.level == 5)
  }

  val clues = Seq(
    LevelClue(position = 3, level = 5),
    ColorClue(position = 3, color = Blue))

  it should "guess its possible cards with a 2 clues on the same card" in {
    val possible = player.possibleCards(onesToThrees, 5, clues)
    possible(3) should contain theSameElementsAs Seq(Card(5, Blue))
  }

  //  it should "guess its possible cards with a 2 clues on another card" in {
  //    player.possibleCards(4, onesToThrees, clues) should
  //      contain theSameElementsAs (foursFives diff Seq(Card(5, Blue)))
  //  }
} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:51,代码来源:PlayerSpec.scala

示例3: DeckSpec

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

import state._

import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.Card._
import hanabi.ai._
import SimpleRules._

@RunWith(classOf[JUnitRunner])
class DeckSpec extends FlatSpec
    with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter
    with StackedDeck {

  "a Deck" should "distribute cards one by one" in {
    val (h, rest) = Deck(allCards.distinct).deal(hands = 5, cardsPerHand = 5)
    val hnds = h.toVector
    println(hnds)
    def expected(lvl: Int) = allColors.map(c => Card(lvl, c)).toVector
    for {
      h <- 0 until 5
      (c, i) <- hnds(h).cards.zipWithIndex
    } c.level should be(5 - i)
  }

  //  it should "allow to try to draw from an empty deck an return unchanged deck" in {
  //  }

} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:37,代码来源:DeckSpec.scala

示例4: HandSpec

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

import state._

import org.scalatest.mockito.MockitoSugar
import org.scalatest.BeforeAndAfter
import org.junit.runner.RunWith
import org.scalatest.OneInstancePerTest
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
import hanabi._
import hanabi.Card._
import hanabi.ai._
import SimpleRules._
import Cards._

@RunWith(classOf[JUnitRunner])
class HandSpec extends FlatSpec
    with Matchers with MockitoSugar with OneInstancePerTest with BeforeAndAfter {

  "a Hand" should "convert color hints to clues" in {
    val h = Hand(2 R, 2 G, 3 B, 1 Y)
    val (clued, clues) = h.hint(Blue)
    h.clues shouldBe empty
    clued.clues shouldBe (Vector(ColorClue(Blue, 2)))
    clues shouldBe (Vector(ColorClue(Blue, 2)))
  }

  it should "convert level hints to clues" in {
    val h = Hand(2 R, 2 G, 3 B, 1 Y)
    val (clued, clues) = h.hint(2)
    clued.clues shouldBe (Vector(LevelClue(2, 0), LevelClue(2, 1)))
    clues shouldBe (Vector(LevelClue(2, 0), LevelClue(2, 1)))
  }

} 
开发者ID:wl-seclin-hashcode,项目名称:hanabi,代码行数:38,代码来源:HandSpec.scala

示例5: DbRunHelperSpec

//设置package包名称以及导入依赖的类
package com.snapswap.db.helpers.runner

import com.opentable.db.postgres.embedded.EmbeddedPostgres
import com.snapswap.db.errors.{EntityNotFound, InternalDataError}
import org.scalatest.{AsyncWordSpec, Matchers, OneInstancePerTest}
//import slick.jdbc.PostgresProfile.api._
import com.snapswap.db.driver.ExtendedPostgresProfile.api._
import slick.lifted.TableQuery

class DbRunHelperSpec
  extends AsyncWordSpec
    with Matchers
    with OneInstancePerTest {

  import runSafe._

  val epg: EmbeddedPostgres = EmbeddedPostgres.start
  val db: Database = Database.forDataSource(epg.getPostgresDatabase, None)
  val tbl: TableQuery[TestTable] = TableQuery[TestTable]

  "SlickRunWrapper" should {
    "replace known errors by appropriate DataError" in {
      val action = for {
        _ <- db.runSafe(tbl.schema.create)
        result <- db.runSafe(sql"""select "IntColumn" from "TestTable" """.as[Int].head)
      } yield result

      action.failed.map { r =>
        r shouldBe a[EntityNotFound]
      }
    }
    "replace unknown errors by InternalDataError with original error description" in {
      val action = for {
        _ <- db.runSafe(tbl.schema.create)
        result <- db.runSafe(DBIO.seq(sql"""select IntColumn from NotExistingTable""".as[Int]).map(_ => ()))
      } yield result

      action.failed map { result =>
        result shouldBe a[InternalDataError]
        result.getMessage should startWith("ERROR: relation \"notexistingtable\" does not exist\n  Position: 23")
      }
    }
    "when success - return Future result" in {
      val action = for {
        _ <- db.runSafe(tbl.schema.create)
        result <- db.runSafe((tbl += 1).andThen(tbl.map(_.IntColumn).result))
      } yield result

      action.map { result =>
        result should equal(Seq(1))
      }
    }
  }

  class TestTable(tag: Tag) extends Table[Int](tag, "TestTable") {
    def IntColumn = column[Int]("IntColumn")

    def * = IntColumn
  }

} 
开发者ID:snap-swap,项目名称:slick-postgres-helpers,代码行数:62,代码来源:DbRunHelperSpec.scala

示例6: ThriftRichClientTest

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

import com.twitter.finagle._
import com.twitter.finagle.stats.StatsReceiver
import org.apache.thrift.protocol.TProtocolFactory
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Mockito._
import org.mockito.Matchers._
import org.scalatest.{OneInstancePerTest, FunSuite}
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar


@RunWith(classOf[JUnitRunner])
class ThriftRichClientTest extends FunSuite with MockitoSugar with OneInstancePerTest {
  object ThriftRichClientMock extends Client[ThriftClientRequest, Array[Byte]] with ThriftRichClient {
    override val protocolFactory: TProtocolFactory = Protocols.binaryFactory()
    override val defaultClientName = "mock_client"

    protected def params: Stack.Params = Stack.Params.empty

    def newService(
      dest: Name,
      label: String
    ): Service[ThriftClientRequest, Array[Byte]] =
      mock[Service[ThriftClientRequest, Array[Byte]]]

    def newClient(
      dest: Name,
      label: String
    ): ServiceFactory[ThriftClientRequest, Array[Byte]] =
      mock[ServiceFactory[ThriftClientRequest, Array[Byte]]]
  }


  test("ThriftRichClientTest newServiceIface takes dest String and stats scoping label arguments") {
    val captor = ArgumentCaptor.forClass(classOf[StatsReceiver])
    val mockBuilder = mock[ServiceIfaceBuilder[String]]
    doReturn("mockServiceIface").when(mockBuilder).newServiceIface(any(), any(), captor.capture())

    val client = spy(ThriftRichClientMock)
    client.newServiceIface("/s/tweetypie/tweetypie", "tweetypie_client")(builder = mockBuilder)

    assert(captor.getValue.toString == "NullStatsReceiver/clnt/tweetypie_client")
    verify(client).newService("/s/tweetypie/tweetypie", "tweetypie_client")
  }

  test("ThriftRichClientTest newServiceIface takes dest Name and stats scoping label arguments") {
    val captor = ArgumentCaptor.forClass(classOf[StatsReceiver])
    val mockBuilder = mock[ServiceIfaceBuilder[String]]
    doReturn("mockServiceIface").when(mockBuilder).newServiceIface(any(), any(), captor.capture())

    val name = Name.empty
    val client = spy(ThriftRichClientMock)
    client.newServiceIface(name, "tweetypie_client")(builder = mockBuilder)

    assert(captor.getValue.toString == "NullStatsReceiver/clnt/tweetypie_client")
    verify(client).newService(name, "tweetypie_client")
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:62,代码来源:ThriftRichClientTest.scala

示例7: DirectToHeapInboundHandlerTest

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

import io.netty.buffer.ByteBuf
import io.netty.channel.embedded.EmbeddedChannel
import org.junit.runner.RunWith
import org.scalacheck.Gen
import org.scalatest.junit.JUnitRunner
import org.scalatest.{FunSuite, OneInstancePerTest}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

@RunWith(classOf[JUnitRunner])
class DirectToHeapInboundHandlerTest extends FunSuite
  with GeneratorDrivenPropertyChecks
  with OneInstancePerTest {

  val channel = new EmbeddedChannel(DirectToHeapInboundHandler)

  test("converts direct to heap") {
    forAll(Gen.alphaStr.suchThat(_.nonEmpty)) { s =>
      val in = channel.alloc.directBuffer(s.length)
      in.setBytes(0, s.getBytes("UTF-8"))

      channel.writeInbound(in)

      val out = channel.readInbound[ByteBuf]

      assert(!out.isDirect)
      assert(in == out)
    }
  }

  test("skips non-ByteBufs") {
    forAll { s: String =>
      channel.writeInbound(s)
      assert(channel.readInbound[String] == s)
    }
  }

  test("works when readIndex is not zero") {
    val in = channel.alloc.directBuffer(4)
    in.writeBytes(Array[Byte](0x1, 0x2, 0x3, 0x4))
    in.readerIndex(1)

    channel.writeInbound(in)

    val out = channel.readInbound[ByteBuf]
    assert(!out.isDirect)
    assert(out.readByte() == 0x2)
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:51,代码来源:DirectToHeapInboundHandlerTest.scala

示例8: TasksSchedulerTest

//设置package包名称以及导入依赖的类
package com.github.mkorman9.districron.logic

import com.github.mkorman9.districron.model.Task
import org.scalamock.function.FunctionAdapter2
import org.scalamock.scalatest.MockFactory
import org.scalatest.{FunSuite, Matchers, OneInstancePerTest}
import org.springframework.scheduling.{TaskScheduler, Trigger}

class TasksSchedulerTest extends FunSuite with Matchers with MockFactory with OneInstancePerTest {
  private val systemTaskSchedulerStub = stub[TaskScheduler]
  private val messageSenderStub = stub[MessageSender]
  private val tasksScheduler = new TasksScheduler(systemTaskSchedulerStub, messageSenderStub)

  test("should schedule task with valid cron expression") {
    // given
    val cronExpression = "0 0 0 0 0"
    val task = Task(
      name = "SomeTask",
      cronExpression = cronExpression,
      globalDistribution = false,
      recipient = "/user/me",
      executionInterval = 15
    )

    // when
    tasksScheduler.schedule(task)

    // then
    (systemTaskSchedulerStub schedule (_: Runnable, _: Trigger)) verify new FunctionAdapter2(
      (runnable: Runnable, trigger: Trigger) =>
        verifyTaskAndMessageSender(runnable, task, messageSenderStub) &&
        verifyScheduledWithGivenCronExpression(trigger, cronExpression)
    )
  }

  private def verifyTaskAndMessageSender(runnable: Runnable, expectedTask: Task, expectedMessageSender: MessageSender): Boolean = runnable match {
    case TaskRunnable(task, messageSender) => task == expectedTask && messageSender == expectedMessageSender
    case _ => false
  }

  private def verifyScheduledWithGivenCronExpression(trigger: Trigger, expectedCron: String): Boolean = trigger match {
    case CronTriggerConfiguration(cronExpression) => cronExpression == expectedCron
    case _ => false
  }
} 
开发者ID:mkorman9,项目名称:districron,代码行数:46,代码来源:TasksSchedulerTest.scala

示例9: FlywayPreparerSpec

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

import org.scalatest.{AsyncWordSpec, Matchers, OneInstancePerTest}
import slick.jdbc.PostgresProfile.api._

class FlywayPreparerSpec
  extends AsyncWordSpec
    with Matchers
    with OneInstancePerTest {

  val db: Database = Postgres.nextDB

  "FlywayPreparer" should {
    "correct apply migration" in {
      val result = db.run(sql"""select count(*) from test_data""".as[Int].head)

      result map { count =>
        count shouldBe 1
      }
    }
  }
} 
开发者ID:snap-swap,项目名称:slick-postgres-testkit,代码行数:23,代码来源:FlywayPreparerSpec.scala

示例10: shouldFindPlayListsOfChannel

//设置package包名称以及导入依赖的类
package com.gmadorell.youtube_sync.module.youtube.test.behaviour

import scala.concurrent.Future

import com.gmadorell.bus.domain.event.EventBus
import com.gmadorell.bus.model.event.Event
import com.gmadorell.youtube_sync.module.youtube.domain.{PlayListRepository, PlayListVideoRepository, VideoRepository}
import com.gmadorell.youtube_sync.module.youtube.domain.model._
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, OneInstancePerTest, WordSpec}
import org.scalatest.concurrent.ScalaFutures

trait YoutubeBehaviourSpec extends WordSpec with MockFactory with ScalaFutures with Matchers with OneInstancePerTest {
  val playListRepository: PlayListRepository           = mock[PlayListRepository]
  val videoRepository: VideoRepository                 = mock[VideoRepository]
  val playListVideoRepository: PlayListVideoRepository = mock[PlayListVideoRepository]
  val eventBus: EventBus                               = mock[EventBus]

  def shouldFindPlayListsOfChannel(channelId: ChannelId, playListsOfChannel: Set[PlayList]): Unit = {
    (playListRepository.findPlayLists _)
      .expects(channelId)
      .once()
      .returning(Future.successful(playListsOfChannel))
  }

  def shouldFindVideosOfPlayList(playListId: PlayListId, videos: Set[Video]): Unit = {
    (videoRepository.findVideos _)
      .expects(playListId)
      .once()
      .returning(Future.successful(videos))
  }

  def shouldPublishEvent(event: Event): Unit = {
    (eventBus.handle _)
      .expects(event)
      .once()
      .returning(Right(Future.successful(())))
  }

  def playListVideoShouldExist(playList: PlayList, video: Video): Unit =
    (playListVideoRepository.exists _)
      .expects(playList, video)
      .once()
      .returning(Future.successful(true))

  def playListVideoShouldNotExist(playList: PlayList, video: Video): Unit =
    (playListVideoRepository.exists _)
      .expects(playList, video)
      .once()
      .returning(Future.successful(false))

  def shouldCreatePlayListVideo(playList: PlayList, video: Video): Unit =
    (playListVideoRepository.create _)
      .expects(playList, video)
      .once()
      .returning(Future.successful(()))
} 
开发者ID:GMadorell,项目名称:youtube_sync,代码行数:58,代码来源:YoutubeBehaviourSpec.scala

示例11: JsonMapperSpec

//设置package包名称以及导入依赖的类
package com.github.gigurra.scalego.serialization.json

import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, OneInstancePerTest, WordSpec}

import scala.language.postfixOps
import org.json4s._
import Extraction._
import JsonMapperSpec._

class JsonMapperSpec
  extends WordSpec
    with MockitoSugar
    with Matchers
    with OneInstancePerTest {

  val dut = new JsonMapper[StringIds]()
  implicit val fmts = dut.jsonFormats

  "JsonMapper" should {

    "Transform a case class into a JValue" in {
      dut.obj2intermediary(TestType(1, "2")) shouldBe decompose(Map("a" -> 1, "b" -> "2"))
    }

    "Transform a JValue into a case class" in {
      dut.intermediary2Obj(decompose(Map("a" -> 1, "b" -> "2")), classOf[TestType]) shouldBe TestType(1, "2")
    }

  }
}

object JsonMapperSpec {
  case class TestType(a: Int, b: String)
} 
开发者ID:GiGurra,项目名称:scalego,代码行数:36,代码来源:JsonMapperSpec.scala

示例12: JdbcSinkTest

//设置package包名称以及导入依赖的类
package io.eels.component.jdbc

import java.sql.DriverManager
import java.util.UUID

import io.eels.Row
import io.eels.datastream.DataStream
import io.eels.schema.{Field, StructType}
import org.scalatest.{Matchers, OneInstancePerTest, WordSpec}

class JdbcSinkTest extends WordSpec with Matchers with OneInstancePerTest {

  Class.forName("org.h2.Driver")
  private val url = "jdbc:h2:mem:" + UUID.randomUUID.toString.replace("-", "")
  private val conn = DriverManager.getConnection(url)
  conn.createStatement().executeUpdate("create table mytab (a integer, b integer, c integer)")

  private val schema = StructType(Field("a"), Field("b"), Field("c"))
  private val frame = DataStream.fromRows(schema, Row(schema, Vector("1", "2", "3")), Row(schema, Vector("4", "5", "6")))

  "JdbcSink" should {
    "write frame to table" in {
      frame.to(JdbcSink(url, "mytab"))
      val rs = conn.createStatement().executeQuery("select count(*) from mytab")
      rs.next()
      rs.getLong(1) shouldBe 2L
      rs.close()
    }
    "create table if createTable is true" in {
      frame.to(JdbcSink(url, "qwerty").withCreateTable(true))
      val rs = conn.createStatement().executeQuery("select count(*) from qwerty")
      rs.next()
      rs.getLong(1) shouldBe 2L
      rs.close()
    }
    "support multiple writers" in {
      val rows = List.fill(10000)(Row(schema, Vector("1", "2", "3")))
      val mframe = DataStream.fromRows(schema, rows)
      val sink = JdbcSink(url, "multithreads").withCreateTable(true).withThreads(4)
      mframe.to(sink)
      val rs = conn.createStatement().executeQuery("select count(*) from multithreads")
      rs.next()
      rs.getLong(1) shouldBe 10000L
      rs.close()
    }
  }
} 
开发者ID:51zero,项目名称:eel-sdk,代码行数:48,代码来源:JdbcSinkTest.scala

示例13: InstaceTypeDBTest

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

import com.dnanexus.{DXEnvironment, DXProject}
import org.scalatest.{BeforeAndAfterEach, FlatSpec, OneInstancePerTest}
import wdl4s.types._
import wdl4s.values._

class InstaceTypeDBTest extends FlatSpec with BeforeAndAfterEach with OneInstancePerTest {

    it should "Work even without access to pricing information" in {
        val db = InstanceTypeDB.genTestDB(false)
        //System.err.println(s"DB=${db.prettyPrint}")

        // parameters are:          RAM,     disk,     cores
        assert(db.choose(None, None, None, None) == "mem1_ssd1_x2")
    }

    it should "Choose reasonable platform instance types" in {
        // parameters are:          RAM,     disk,     cores
        val db = InstanceTypeDB.genTestDB(true)
        assert(db.choose(None, None, None, None) == "mem1_ssd1_x2")
        assert(db.choose(None, Some(3*1024), Some(100), Some(5)) == "mem1_ssd1_x8")
        assert(db.choose(None, Some(2*1024), Some(20), None) == "mem1_ssd1_x2")
        assert(db.choose(None, Some(30*1024), Some(128), Some(8)) == "mem3_ssd1_x8")

        assert(db.apply(None,
                        Some(WdlString("3 GB")),
                        Some(WdlString("local-disk 10 HDD")),
                        Some(WdlString("1"))) == "mem1_ssd1_x2")
        assert(db.apply(None,
                        Some(WdlString("37 GB")),
                        Some(WdlString("local-disk 10 HDD")),
                        Some(WdlString("6"))) == "mem3_ssd1_x8")
        assert(db.apply(None,
                        Some(WdlString("2 GB")),
                        Some(WdlString("local-disk 100 HDD")),
                        None) == "mem1_ssd1_x8")
        assert(db.apply(None,
                        Some(WdlString("2.1GB")),
                        Some(WdlString("local-disk 100 HDD")),
                        None) == "mem1_ssd1_x8")

        assert(db.apply(Some(WdlString("mem3_ssd1_x8")), None, None, None) == "mem3_ssd1_x8")

        assert(db.apply(None,
                        Some(WdlString("235 GB")),
                        Some(WdlString("local-disk 550 HDD")),
                        Some(WdlString("32"))) == "mem3_ssd1_x32")
        assert(db.apply(Some(WdlString("mem3_ssd1_x32")), None, None, None) == "mem3_ssd1_x32")
    }
} 
开发者ID:dnanexus-rnd,项目名称:dxWDL,代码行数:52,代码来源:InstanceTypeDBTest.scala

示例14: shouldFindPokerGame

//设置package包名称以及导入依赖的类
package com.lambtors.poker_api.module.poker.behaviour

import scala.concurrent.Future

import com.lambtors.poker_api.module.poker.domain.PokerGameRepository
import com.lambtors.poker_api.module.poker.domain.model.{GameId, PokerGame}
import org.scalactic.TypeCheckedTripleEquals
import org.scalamock.scalatest.MockFactory
import org.scalatest.{Matchers, OneInstancePerTest, WordSpec}
import org.scalatest.concurrent.ScalaFutures

trait PokerBehaviourSpec
    extends WordSpec
    with Matchers
    with TypeCheckedTripleEquals
    with MockFactory
    with OneInstancePerTest
    with ScalaFutures
    with MockedPokerGameRepository

trait MockedPokerGameRepository extends MockFactory {
  protected val pokerGameRepository: PokerGameRepository = mock[PokerGameRepository]

  def shouldFindPokerGame(gameId: GameId, pokerGame: PokerGame): Unit =
    (pokerGameRepository.search _).expects(gameId).once().returning(Future.successful(Some(pokerGame)))

  def shouldNotFindPokerGame(gameId: GameId): Unit =
    (pokerGameRepository.search _).expects(gameId).once().returning(Future.successful(None))

  def shouldInsertPokerGame(pokerGame: PokerGame): Unit =
    (pokerGameRepository.insert _).expects(pokerGame).once().returning(Future.successful(Unit))
} 
开发者ID:lambtors,项目名称:poker-api,代码行数:33,代码来源:PokerBehaviourSpec.scala

示例15: ThoughtServiceSpec

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

import com.twitter.util.{Await, Future => TFuture}
import jarta.thoughtservice.model.ThoughtRepository
import jarta.thoughtservice.thriftscala.Thought
import jarta.thoughtservice.thriftscala.ThoughtService.{DeleteThought, GetThought, InsertThought}
import org.mockito.Mockito.{verify, when}
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{FlatSpec, Matchers, OneInstancePerTest}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future => SFuture}

class ThoughtServiceSpec extends FlatSpec with MockitoSugar with Matchers with OneInstancePerTest {

  private val repository = mock[ThoughtRepository]
  private val service = new ThoughtService(repository)
  private val newThought = Thought(0, "title")

  behavior of classOf[ThoughtService].getSimpleName

  "getThought" should "call the repository with the given id" in {
    when(repository.select(1)).thenReturn(SFuture(None))
    service.getThought(GetThought.Args(1))
    verify(repository).select(1)
  }

  it should "convert a None result to null" in {
    when(repository.select(1)).thenReturn(SFuture(None))
    Await.result(service.getThought(GetThought.Args(1))).success.get shouldBe Await.result(TFuture(null))
  }

  "insertThought" should "call the repository with the given thought" in {
    when(repository.insert(newThought)).thenReturn(SFuture(Thought(1, "title")))
    service.insertThought(InsertThought.Args(newThought))
    verify(repository).insert(newThought)
  }

  "deleteThought" should "call the repository with the given id" in {
    when(repository.delete(1)).thenReturn(SFuture(1))
    service.deleteThought(DeleteThought.Args(1))
    verify(repository).delete(1)
  }
} 
开发者ID:lbunschoten,项目名称:jarta,代码行数:45,代码来源:ThoughtServiceSpec.scala


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