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

Scala Mockito类代码示例

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

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



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

示例1: PaginatedResponseRetrieverSpec

//设置package包名称以及导入依赖的类
package com.dwolla.awssdk.utils

import com.amazonaws.services.ecs.AmazonECSAsync
import com.amazonaws.services.ecs.model.{ListClustersRequest, ListClustersResult, ListContainerInstancesRequest, ListContainerInstancesResult}
import com.dwolla.awssdk.AmazonAsyncMockingImplicits._
import com.dwolla.awssdk.utils.PaginatedResponseRetriever._
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

import scala.collection.JavaConverters._

class PaginatedResponseRetrieverSpec(implicit ee: ExecutionEnv) extends Specification with Mockito {

  trait Setup extends Scope {
    val mockEcsClient = mock[AmazonECSAsync]
  }

  "PaginatedResponseRetriever" should {
    "make all the requests necessary to fetch all paginated results" in new Setup {
      def reqWithNextToken(x: Option[Int]) = new ListContainerInstancesRequest().withCluster("cluster1").withNextToken(x.map(i ? s"next-token-$i").orNull)

      def res(x: Int, y: Option[Int] = None) = Right(new ListContainerInstancesResult().withContainerInstanceArns(s"arn$x").withNextToken(y.map(i ? s"next-token-$i").orNull))

      val pages = 1 to 50
      val pairs = pages.sliding(2).toSeq.map {
        case Vector(1, y) ? reqWithNextToken(None) ? res(1, Option(y))
        case Vector(x, y) if x > 1 && y < pages.last ? reqWithNextToken(Option(x)) ? res(x, Option(y))
        case Vector(x, _) ? reqWithNextToken(Option(x)) ? res(x, None)
      }

      mockedMethod(mockEcsClient.listContainerInstancesAsync) answers (pairs: _*)

      val output = fetchAll(() ? new ListContainerInstancesRequest().withCluster("cluster1"),mockEcsClient.listContainerInstancesAsync)
        .map(_.flatMap(_.getContainerInstanceArns.asScala.toList))

      output must containTheSameElementsAs(pages.dropRight(1).map(x ? s"arn$x")).await
    }

    "support default request factory" in new Setup {
      new ListClustersResult() completes mockEcsClient.listClustersAsync

      val output = fetchAllWithDefaultRequestsVia(mockEcsClient.listClustersAsync)

      output must contain(new ListClustersResult()).await
    }

    "support builder syntax with factory as initial parameter" in new Setup {
      new ListClustersResult() completes mockEcsClient.listClustersAsync

      val output = fetchAllWithRequestsLike(() ? new ListClustersRequest).via(mockEcsClient.listClustersAsync)

      output must contain(new ListClustersResult()).await
    }
  }
} 
开发者ID:Dwolla,项目名称:scala-aws-utils,代码行数:58,代码来源:PaginatedResponseRetrieverSpec.scala


示例2: UserControllerSpec

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

import models.User
import org.mockito.Mockito._
import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.test._
import play.api.test.Helpers._
import services.UserServiceApi
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import scala.concurrent.Future

@RunWith(classOf[JUnitRunner])
class UserControllerSpec extends PlaySpecification with Mockito {

  "User Controller " should{

    val service=mock[UserServiceApi]
    val controller=new UserController(service)

    "list users" in new WithApplication() {

      when(service.getUser).thenReturn(Future(List(User(1,"himani","[email protected]","98765432","himani"))))

      val res=call(controller.list,FakeRequest(GET,"/list"))

      status(res) must equalTo(OK)
    }

    "add users" in new WithApplication() {

      when(service.insertUser(1,"himani","[email protected]","22510498","himani")).thenReturn(Future(1))
      val res=call(controller.add,FakeRequest(GET,"/list"))
      status(res) must equalTo(OK)
    }

    "delete users" in new WithApplication() {
      when(service.deleteUser(1)).thenReturn(Future(1))
      val res=call(controller.delete(1),FakeRequest(GET,"/list"))
      status(res) must equalTo(SEE_OTHER)
    }

    "update users" in new WithApplication() {
      when(service.updateUser(1,"himani","[email protected]","22598609","himani")).thenReturn(Future(1))
      val res=call(controller.update,FakeRequest(GET,"/list"))
      status(res) must equalTo(OK)
    }

  }
} 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:53,代码来源:UserControllerSpec.scala


示例3: ProgLanguageControllerSpec

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

import models.ProgLanguage
import org.mockito.Mockito._
import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.test._
import play.api.test.Helpers._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import services.ProgLanguageApi

import scala.concurrent.Future

@RunWith(classOf[JUnitRunner])
class ProgLanguageControllerSpec extends PlaySpecification with Mockito {


  "Prog Language Controller" should {

    val service = mock[ProgLanguageApi]
    val controller = new ProgLanguageController(service)

    "list languages" in new WithApplication() {

      when(service.getProg()).thenReturn(Future(List(ProgLanguage(1,"scala"))))

      val res = call(controller.list, FakeRequest(GET, "/listprog"))
      status(res) must equalTo(OK)
    }

    "list languages by id" in new WithApplication() {
      when(service.getProgId(1)).thenReturn(Future(List(ProgLanguage(1,"scala"))))
      val res = call(controller.listById, FakeRequest(GET, "/listprog").withSession("id"->"1"))
      status(res) must equalTo(OK)
    }

    "add new language" in new WithApplication() {
      when(service.insertProg(1,"scala")).thenReturn(Future(1))
      val res=call(controller.add,FakeRequest(GET,"/add").withSession("id"->"1"))
      status(res) must equalTo(OK)
    }

    "delete record by id" in new WithApplication() {

      when(service.deleteProg("scala")).thenReturn(Future(1))
      val res=call(controller.delete("scala"),FakeRequest(GET,"/deleteprog"+"/scala").withSession("id"->"1"))
      status(res) must equalTo(SEE_OTHER)
    }
  }
} 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:53,代码来源:ProgLanguageControllerSpec.scala


示例4: ProgLanguageServiceTest

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

import models.ProgLanguage
import org.mockito.Mockito._
import org.specs2.mock.Mockito
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.test._
import play.api.test.Helpers._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import repository.ProgLanguageRepo
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

@RunWith(classOf[JUnitRunner])
class ProgLanguageServiceTest extends PlaySpecification with Mockito {

  "Programming language Service" should {

    val service=mock[ProgLanguageRepo]
    val controller=new ProgLanguageService(service)

    "get records"in new WithApplication() {

      when(service.getAll()).thenReturn(Future(List(ProgLanguage(1,"scala"))))
        val res=controller.getProg()
        val response=Await.result(res,Duration.Inf)
        response===List(ProgLanguage(1,"scala"))
    }

    "get records by id" in new WithApplication{
      when(service.getProgLanguage(1)).thenReturn(Future(List(ProgLanguage(1,"scala"))))
      val res=controller.getProgId(1)
      val response=Await.result(res,Duration.Inf)
      response===List(ProgLanguage(1,"scala"))
    }

    "add records" in new WithApplication() {
      when(service.insert(1,"scala")).thenReturn(Future(1))
      val res=controller.insertProg(1,"scala")
      val response=Await.result(res,Duration.Inf)
      response===1
    }

    "update records" in new WithApplication() {
      when(service.update(1,"scala")).thenReturn(Future(1))
      val res=controller.updateProg(1,"scala")
      val response=Await.result(res,Duration.Inf)
      response===1
    }

    "delete record" in new WithApplication() {
      when(service.delete("scala")).thenReturn(Future(1))
      val res=controller.deleteProg("scala")
      val response=Await.result(res,Duration.Inf)
      response===1
    }
  }

} 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:62,代码来源:ProgLanguageServiceTest.scala


示例5: ResultsSpec

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

import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.{Arbitrary, Gen}
import org.specs2._
import org.specs2.mock.Mockito
import org.specs2.specification.core._
import roc.postgresql.failures.ElementNotFoundFailure

final class ResultsSpec extends Specification with ScalaCheck with Mockito { def is = s2"""

  Row
    get(column) must throw ElementNotFound failure for unknown column name  $columnNotFound
                                                                           """
  
  val columnNotFound = forAll { sym: Symbol =>
    val row = new Row(List.empty[Element])
    row.get(sym) must throwA[ElementNotFoundFailure]
  }

  lazy val genSymbol: Gen[Symbol] = for {
    str <-  arbitrary[String]
  } yield Symbol(str)
  implicit lazy val arbitrarySymbol: Arbitrary[Symbol] =
    Arbitrary(genSymbol)
} 
开发者ID:finagle,项目名称:roc,代码行数:29,代码来源:ResultsSpec.scala


示例6: CakeTestSpecification

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

import java.util
import javax.persistence.{TypedQuery, EntityManager}

import org.specs2.mutable.Specification
import org.specs2.mock.Mockito


class CakeTestSpecification extends Specification with Mockito  {
  trait MockEntitManager {
    val em = mock[EntityManager]

    def expect(f: (EntityManager) => Any) {
      f(em)
    }
  }

  "findAll should use the EntityManager's typed queries" in {
    val query = mock[TypedQuery[User]]
    val users: java.util.List[User] = new util.ArrayList[User]()

    val userService = new DefaultUserServiceComponent
      with UserRepositoryJPAComponent
      with MockEntitManager
    userService.expect { em =>
      em.createQuery("from User", classOf[User]) returns query
      query.getResultList returns users
    }

    userService.userService.findAll must_== users
  }
} 
开发者ID:johnnyqian,项目名称:CakePatternInDepth,代码行数:34,代码来源:CakeTestSpecification.scala


示例7: UserServiceSuite

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

import org.scalatest.FunSuite
import org.specs2.mock.Mockito


class UserServiceSuite extends FunSuite
with Mockito
with UserServiceComponent
with UserRepositoryComponent {
  lazy val userRepository = mock[UserRepository]
  lazy val userService = mock[UserService]

  val user = new User("test", "test")
  userRepository.authenticate(any[User]) returns user

  test("testAuthenticate") {
    assert(userRepository.authenticate(user) == user)
  }
} 
开发者ID:johnnyqian,项目名称:CakePatternPractise,代码行数:21,代码来源:UserServiceSuite.scala


示例8: JsonRequestSpec

//设置package包名称以及导入依赖的类
package play.api.libs.ws.ahc

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.util.ByteString
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.api.libs.json.{ JsString, Json }
import play.api.libs.ws.JsonBodyWritables
import play.libs.ws.DefaultObjectMapper


class JsonRequestSpec extends Specification with Mockito with AfterAll with JsonBodyWritables {
  sequential

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

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

  "set a json node" in {
    val jsValue = Json.obj("k1" -> JsString("v1"))
    val client = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(jsValue)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("application/json")
    ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
  }

  "set a json node using the default object mapper" in {
    val objectMapper = DefaultObjectMapper.instance

    implicit val jsonReadable = body(objectMapper)
    val jsonNode = objectMapper.readTree("""{"k1":"v1"}""")
    val client = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(jsonNode)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("application/json")
    ByteString.fromArray(req.getByteData).utf8String must be_==("""{"k1":"v1"}""")
  }
} 
开发者ID:playframework,项目名称:play-ws,代码行数:51,代码来源:JsonRequestSpec.scala


示例9: XMLRequestSpec

//设置package包名称以及导入依赖的类
package play.api.libs.ws.ahc

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.util.ByteString
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.AfterAll
import play.api.libs.ws.{ XML, XMLBodyReadables, XMLBodyWritables }
import play.shaded.ahc.org.asynchttpclient.{ Response => AHCResponse }

import scala.xml.Elem


class XMLRequestSpec extends Specification with Mockito with AfterAll {
  sequential

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

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

  "write an XML node" in {
    import XMLBodyWritables._

    val xml = XML.parser.loadString("<hello><test></test></hello>")
    val client = mock[StandaloneAhcWSClient]
    val req = new StandaloneAhcWSRequest(client, "http://playframework.com/", null)
      .withBody(xml)
      .asInstanceOf[StandaloneAhcWSRequest]
      .buildRequest()

    req.getHeaders.get("Content-Type") must be_==("text/xml")
    ByteString.fromArray(req.getByteData).utf8String must be_==("<hello><test/></hello>")
  }

  "read an XML node" in {
    import XMLBodyReadables._

    val ahcResponse = mock[AHCResponse]
    ahcResponse.getResponseBody returns "<hello><test></test></hello>"
    val response = new StandaloneAhcWSResponse(ahcResponse)

    val expected = XML.parser.loadString("<hello><test></test></hello>")
    val actual = response.body[Elem]
    actual must be_==(expected)
  }
} 
开发者ID:playframework,项目名称:play-ws,代码行数:51,代码来源:XMLRequestSpec.scala


示例10: EmployeeControllerSpec

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

import org.specs2.mock.Mockito
import play.api.libs.json.Json
import play.api.mvc._
import play.api.test._

import scala.concurrent.Future

class EmployeeControllerSpec  extends PlaySpecification with Mockito with Results {

  val mockedRepo = mock[EmployeeRepository]
  val employeeController= new EmployeeController(mockedRepo)

  "EmployeeController " should {

    "create a employee" in {
        val emp = Employee("sky", "[email protected]", "knoldus", "Senior Consultant")
        mockedRepo.insert(emp) returns Future.successful(1)

        val result = employeeController.create().apply(FakeRequest().withBody(Json.toJson(emp)))
        val resultAsString = contentAsString(result)
        resultAsString === """{"status":"success","data":{"id":1},"msg":"Employee has been created successfully."}"""
      }

    "update a employee" in {
      val updatedEmp = Employee("Satendra", "[email protected]", "knoldus", "Senior Consultant", Some(1))
      mockedRepo.update(updatedEmp) returns Future.successful(1)

      val result = employeeController.update().apply(FakeRequest().withBody(Json.toJson(updatedEmp)))
      val resultAsString = contentAsString(result)
      resultAsString === """{"status":"success","data":"{}","msg":"Employee has been updated successfully."}"""
    }

    "edit a employee" in {
      val emp = Employee("sky", "[email protected]", "knoldus", "Senior Consultant",Some(1))
      mockedRepo.getById(1) returns Future.successful(Some(emp))
      val result = employeeController.edit(1).apply(FakeRequest())
      val resultAsString = contentAsString(result)
      resultAsString === """{"status":"success","data":{"name":"sky","email":"[email protected]","companyName":"knoldus","position":"Senior Consultant","id":1},"msg":"Getting Employee successfully"}"""
    }

    "delete a employee" in {
      mockedRepo.delete(1) returns Future.successful(1)
      val result = employeeController.delete(1).apply(FakeRequest())
      val resultAsString = contentAsString(result)
      resultAsString === """{"status":"success","data":"{}","msg":"Employee has been deleted successfully."}"""
    }
    "get all list" in {
      val emp = Employee("sky", "[email protected]", "knoldus", "Senior Consultant",Some(1))
      mockedRepo.getAll() returns Future.successful(List(emp))
      val result = employeeController.list().apply(FakeRequest())
      val resultAsString = contentAsString(result)
      resultAsString === """{"status":"success","data":[{"name":"sky","email":"[email protected]","companyName":"knoldus","position":"Senior Consultant","id":1}],"msg":"Getting Employee list successfully"}"""
    }

  }

} 
开发者ID:limavi,项目名称:migrana,代码行数:60,代码来源:EmployeeControllerSpec.scala


示例11: SecuredSpec

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

import db.scalikejdbc.{InMemDb, UserJdbc}
import org.intracer.wmua.User
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import play.api.mvc.{RequestHeader, Security, Session}

class SecuredSpec extends Specification with Mockito with InMemDb {

  sequential

  val userDao = UserJdbc

  def mockRequest(username: String): RequestHeader = {
    val request = mock[RequestHeader]
    val session = mock[Session]
    session.get(Security.username) returns Some(username)
    request.session returns session
    request
  }

  "user" should {
    "load from db" in {
      inMemDbApp {
        val username = "[email protected]"
        val user = User("fullname", username, None, Set("jury"), Some("password hash"), Some(10))

        val created = userDao.create(user)

        val request: RequestHeader = mockRequest(username)
        new Secured {}.userFromRequest(request) === Some(created)
      }
    }

    "be None if not in db" in {
      inMemDbApp {
        val username = "user login"
        val user = User("fullname", username, None, Set("jury"), Some("password hash"), Some(10))

        val created = userDao.create(user)

        val request: RequestHeader = mockRequest(username + " other")
        new Secured {}.userFromRequest(request) === None
      }
    }

  }

} 
开发者ID:intracer,项目名称:wlxjury,代码行数:51,代码来源:SecuredSpec.scala


示例12:

//设置package包名称以及导入依赖的类
import akka.http.scaladsl.testkit.ScalatestRouteTest
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport
import handlers.OAuth2DataHandler
import http.HttpService
import io.circe.generic.auto._
import io.circe.syntax._
import org.scalatest.{ Matchers, WordSpec }
import org.specs2.mock.Mockito
import services._
import utils.CirceCommonCodecs

trait SpecBase extends WordSpec
    with Matchers with ScalatestRouteTest with Mockito with FailFastCirceSupport
    with CirceCommonCodecs {

  val databaseService: DatabaseService = mock[DatabaseService]
  val accountsService: AccountsService = mock[AccountsService]
  val oAuthClientsService: OAuthClientsService = mock[OAuthClientsService]
  val oAuthAccessTokensService: OAuthAccessTokensServiceImpl = mock[OAuthAccessTokensServiceImpl]
  val cacheService: CachingService = mock[CachingService]
  val moviesService: MoviesService = mock[MoviesService]
  val reservationService: ReservationService = mock[ReservationService]

  val oauth2DataHandler = new OAuth2DataHandler(
    oAuthClientsService,
    oAuthAccessTokensService, accountsService
  )

  val httpService = new HttpService(moviesService, oAuthClientsService,
    oAuthAccessTokensService, accountsService, cacheService, reservationService)
} 
开发者ID:ziyasal,项目名称:Reserveon,代码行数:32,代码来源:SpecBase.scala


示例13: ChatSpec

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

import akka.actor.ActorSystem
import org.specs2.mock.Mockito
import play.api.i18n.MessagesApi
import play.api.test._

class ChatSpec extends PlaySpecification with Mockito {

  val mockMessagesApi = mock[MessagesApi]
  val mockActorSystem = mock[ActorSystem]
  val app = new Chat(mockMessagesApi, mockActorSystem)
  val additionalConf = Map("play.crypto.secret" -> "_Zgs2h=lF1BuKGAUNb5bsL<nQ62H=4xWYlcOT;NEmepkbjdb9PFl;hJ0ZzG/YkD=")

  "Chat" should {
    "redirect to index during leaving" in {
      val leave = app.leave()(FakeRequest())
      status(leave) must equalTo(SEE_OTHER)
      redirectLocation(leave) must beSome.which(_ == "/")
    }

    "redirect to chat after defining nickname" in new WithApplication(app = FakeApplication(additionalConfiguration = additionalConf)) {
      val Mickey = "Mickey Mouse"
      val nickname = route(FakeRequest(POST, "/nickname").withFormUrlEncodedBody("nickname" -> Mickey)).get
      status(nickname) must equalTo(SEE_OTHER)
      redirectLocation(nickname) must beSome.which(_ == "/chat")
      session(nickname).get("user") must beSome(Mickey)
    }

    "bad request for empty nickname" in new WithApplication(app = FakeApplication(additionalConfiguration = additionalConf)) {
      val result = route(FakeRequest(POST, "/nickname").withFormUrlEncodedBody("nickname" -> "")).get
      status(result) must equalTo(BAD_REQUEST)
    }

    "redirect to index instead chat if session is empty" in {
      val chat = app.chat()(FakeRequest())
      status(chat) must equalTo(SEE_OTHER)
      redirectLocation(chat) must beSome.which(_ == "/")
    }

    "open chat room" in new WithApplication(app = FakeApplication(additionalConfiguration = additionalConf)) {
      val john = "johnsmith"
      val chat = route(FakeRequest(GET, "/chat").withSession("user" -> john)).get
      status(chat) must equalTo(OK)
      contentAsString(chat) must contain(s"User : $john")
    }
  }
} 
开发者ID:onegrx,项目名称:playakkachat,代码行数:49,代码来源:ChatSpec.scala


示例14: CloudflareApiExecutorSpec

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

import org.apache.http.HttpResponse
import org.apache.http.client.methods.{CloseableHttpResponse, HttpRequestBase}
import org.apache.http.impl.client.CloseableHttpClient
import org.specs2.concurrent.ExecutionEnv
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope

class CloudflareApiExecutorSpec(implicit ee: ExecutionEnv) extends Specification with Mockito {

  trait Setup extends Scope {
    val authorization = CloudflareAuthorization("email", "key")
    val mockHttpClient = mock[CloseableHttpClient]

    val executor = new CloudflareApiExecutor(authorization) {
      override lazy val httpClient = mockHttpClient
    }
  }

  "Cloudflare API Executor" should {
    "add required headers to requests" in new Setup {
      val request = mock[HttpRequestBase]
      private val response = mock[CloseableHttpResponse]

      mockHttpClient.execute(request) returns response

      val output = executor.fetch(request)(res ? Some(res))

      output must beSome(response.asInstanceOf[HttpResponse]).await

      there was one(request).addHeader("X-Auth-Email", authorization.email)
      there was one(request).addHeader("X-Auth-Key", authorization.key)
      there was one(request).addHeader("Content-Type", "application/json")
      there was one(response).close()
    }

    "close the HttpClient on close" in new Setup {
      executor.close()

      there was one(mockHttpClient).close()
    }
  }

} 
开发者ID:Dwolla,项目名称:scala-cloudflare,代码行数:47,代码来源:CloudflareApiExecutorSpec.scala


示例15: S3RelationTest

//设置package包名称以及导入依赖的类
package com.knoldus.spark.s3

import org.apache.spark.sql.SQLContext
import org.apache.spark.{SparkConf, SparkContext}
import org.scalatest.{BeforeAndAfterEach, FunSuite}
import org.specs2.mock.Mockito

class S3RelationTest extends FunSuite with Mockito with BeforeAndAfterEach {

  var sparkConf: SparkConf = _
  var sc: SparkContext = _
  var sqlContext: SQLContext = _

  override def beforeEach() {
    sparkConf = new SparkConf().setMaster("local").setAppName("Test S3 Relation")
    sc = new SparkContext(sparkConf)
    sqlContext = new SQLContext(sc)
  }

  override def afterEach() {
    sc.stop()
  }


  test("get schema") {
    val dataFrame = sqlContext.read.json(getClass.getResource("/sample.json").getPath)
    val relation = S3Relation("path", "access_key", "secretKey", "bucket", "json", dataFrame, sqlContext)
    val result = relation.schema
    assert(result === dataFrame.schema)
  }

} 
开发者ID:knoldus,项目名称:spark-s3,代码行数:33,代码来源:S3RelationTest.scala


示例16: UploaderTest

//设置package包名称以及导入依赖的类
package com.knoldus.spark.s3

import java.io.File

import com.amazonaws.AmazonClientException
import com.amazonaws.services.s3.model.{PutObjectRequest, PutObjectResult}
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.transfer.{MultipleFileUpload, TransferManager}
import org.mockito.Mockito._
import org.scalatest.FunSuite
import org.specs2.mock.Mockito

class UploaderTest extends FunSuite with Mockito {

  private val transferManager = mock[TransferManager]
  private val amazonS3Client = mock[AmazonS3Client]
  private val multipleFileUpload = mock[MultipleFileUpload]
  private val putObjectResult = mock[PutObjectResult]
  private val file = new File("src/test/resources/sample.json")
  private val filePath = "src/test/resources/sample.json"
  private val bucket = "bucket"
  private val uploader = new Uploader(transferManager)

  test("upload is successful") {
    when(transferManager.uploadDirectory(any[String], any[String], any[File], any[Boolean])).thenReturn(multipleFileUpload)
    val result = uploader.uploadDirectory(file, filePath, bucket)
    assert(result)
  }

  test("upload is not successful") {
    when(transferManager.uploadDirectory(any[String], any[String], any[File], any[Boolean])).thenThrow(new IllegalArgumentException)
    val result = uploader.uploadDirectory(file, filePath, bucket)
    assert(!result)
  }

  test("upload partition is successful") {
    when(transferManager.getAmazonS3Client).thenReturn(amazonS3Client)
    when(amazonS3Client.putObject(any[PutObjectRequest])).thenReturn(putObjectResult)
    val result = uploader.uploadPartition(new File("src"), filePath, bucket)
    assert(result)
  }

  test("upload partition is not successful") {
    when(transferManager.getAmazonS3Client).thenReturn(amazonS3Client)
    when(amazonS3Client.putObject(any[PutObjectRequest])).thenThrow(new AmazonClientException("exception"))
    val result = uploader.uploadPartition(new File("src"), filePath, bucket)
    assert(!result)
  }

} 
开发者ID:knoldus,项目名称:spark-s3,代码行数:51,代码来源:UploaderTest.scala


示例17: MpacFacadeTest

//设置package包名称以及导入依赖的类
package ch.mibex.bamboo.shipit.mpac

import com.atlassian.marketplace.client.MarketplaceClient
import com.atlassian.marketplace.client.api.AddonQuery
import org.junit.runner.RunWith
import org.mockito.Answers._
import org.mockito.Mockito.withSettings
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import org.specs2.specification.Scope


@RunWith(classOf[JUnitRunner])
class MpacFacadeTest extends Specification with Mockito {

  "find plug-in by key" should {

    "yield none if unknown" in new PluginNotFoundContext {
      client.findPlugin("UNKNOWN PLUGIN") must beRight(None)
    }

  }

  class PluginNotFoundContext extends Scope {
    val mpac = mock[MarketplaceClient](withSettings.defaultAnswer(RETURNS_DEEP_STUBS.get))
    // val plugin = mock[Plugin] // we cannot mock Plugin as it is final
    mpac.addons().getByKey(anyString, any[AddonQuery]) returns com.atlassian.fugue.Option.none()
    val client = new MpacFacade(mpac)
  }

} 
开发者ID:mibexsoftware,项目名称:shipit2marketplace,代码行数:33,代码来源:MpacFacadeTest.scala


示例18: MockedUserDaoSpec

//设置package包名称以及导入依赖的类
import org.junit.runner.RunWith
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class MockedUserDaoSpec extends Specification with Mockito {

  "The UserService" should {
    "return a list of three users" in {
      UserService.registeredUsers.length must be equalTo(3)
    }
  }

  object UserService extends services.UserServiceT {
    override val userDao = mock[dbaccess.UserDaoT]
    import models.User
    userDao.registeredUsers returns List(User(1,"Helge"), User(2,"Helga"), User(3,"Tina"))
  }

} 
开发者ID:ioaccept,项目名称:pizza,代码行数:22,代码来源:MockedUserDaoSpec.scala


示例19: AuthTokenCleanerSpec

//设置package包名称以及导入依赖的类
package io.soheila.um.jobs

import java.time.LocalDateTime
import java.util.UUID

import akka.actor.{ ActorSystem, Props }
import akka.testkit.{ ImplicitSender, TestKit }
import io.soheila.um.entities.AuthToken
import io.soheila.um.jobs.AuthTokenCleaner.Clean
import io.soheila.um.services.auths.AuthTokenService
import io.soheila.um.utils.UMClock
import org.specs2.SpecificationLike
import org.specs2.mock.Mockito
import org.specs2.specification.AfterAll
import org.specs2.specification.core.SpecStructure

import scala.concurrent.Future
import scala.concurrent.duration._
import akka.testkit._

class AuthTokenCleanerSpec extends TestKit(ActorSystem()) with SpecificationLike with Mockito with ImplicitSender with AfterAll {
  override def is: SpecStructure =
    s2"""
      should request token clean up when receiving Clean message $e1
    """

  10.seconds.dilated

  val authTokenServiceMock = mock[AuthTokenService]
  val clockMock = mock[UMClock]

  val actor = system.actorOf(Props(new AuthTokenCleaner(authTokenServiceMock, clockMock)))

  def e1 = {
    val authToken = AuthToken(UUID.randomUUID(), UUID.randomUUID(), LocalDateTime.now())
    authTokenServiceMock.clean returns Future.successful(Seq(authToken))
    clockMock.now returns LocalDateTime.now

    actor ! Clean

    Thread.sleep(1000)

    there was one(authTokenServiceMock).clean
  }

  override def afterAll = {
    TestKit.shutdownActorSystem(system)
  }
} 
开发者ID:esfand-r,项目名称:soheila-um,代码行数:50,代码来源:AuthTokenCleanerSpec.scala


示例20: AccountJobSchedulerSpec

//设置package包名称以及导入依赖的类
package io.soheila.um.jobs

import akka.actor.{ ActorRef, ActorSystem }
import akka.testkit.TestProbe
import org.specs2.Specification
import org.specs2.mock.Mockito
import org.specs2.specification.core.SpecStructure
import scala.concurrent.duration._

class AccountJobSchedulerSpec extends Specification with Mockito {
  override def is: SpecStructure =
    s2"""
      Schedular should schedule the AuthToken cleaner and start it with a Clean message $e1
    """

  implicit val system = ActorSystem()

  val probe = TestProbe("test")
  val mockedActorRef: ActorRef = probe.ref

  def e1 = {
    val accountJobSchedularMock = new AccountJobScheduler(system, mockedActorRef)

    val message = probe.expectMsg(500 millis, AuthTokenCleaner.Clean)
    message must not beNull
  }
} 
开发者ID:esfand-r,项目名称:soheila-um,代码行数:28,代码来源:AccountJobSchedulerSpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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