本文整理汇总了Scala中org.specs2.mock.Mockito类的典型用法代码示例。如果您正苦于以下问题:Scala Mockito类的具体用法?Scala Mockito怎么用?Scala Mockito使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Mockito类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
}
示例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)
}
}
}
示例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)
}
}
}
示例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
}
}
}
示例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)
}
示例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
}
}
示例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)
}
}
示例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"}""")
}
}
示例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)
}
}
示例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"}"""
}
}
}
示例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
}
}
}
}
示例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)
}
示例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")
}
}
}
示例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()
}
}
}
示例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)
}
}