本文整理汇总了Scala中org.scalatest.mock.MockitoSugar类的典型用法代码示例。如果您正苦于以下问题:Scala MockitoSugar类的具体用法?Scala MockitoSugar怎么用?Scala MockitoSugar使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MockitoSugar类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: AbstractActorSpec
//设置package包名称以及导入依赖的类
package name.mikulskibartosz.demo.akka.actors
import akka.actor.ActorSystem
import akka.testkit.{ImplicitSender, DefaultTimeout, TestKit}
import name.mikulskibartosz.demo.akka.service.Service
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import scala.util.Try
abstract class AbstractActorSpec extends TestKit(ActorSystem()) with DefaultTimeout with ImplicitSender
with WordSpecLike with Matchers with BeforeAndAfterAll with MockitoSugar {
override def afterAll() = {
super.afterAll()
shutdown()
}
def createServiceReturning(value: Try[Int]) = {
val service = mock[Service]
when(service.generate()).thenReturn(value)
service
}
}
示例2: SourceTrackingMonitorTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.builder
import com.twitter.finagle.{Failure, RequestException}
import java.io.IOException
import java.util.logging.{Level, Logger}
import org.junit.runner.RunWith
import org.mockito.Matchers.{any, eq => mockitoEq}
import org.mockito.Mockito.{never, verify}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
@RunWith(classOf[JUnitRunner])
class SourceTrackingMonitorTest extends FunSuite with MockitoSugar {
test("handles unrolling properly") {
val logger = mock[Logger]
val monitor = new SourceTrackingMonitor(logger, "qux")
val e = new Exception
val f1 = new Failure("foo", Some(e), sources = Map(Failure.Source.Service -> "tweet"))
val f2 = new Failure("bar", Some(f1))
val exc = new RequestException(f2)
exc.serviceName = "user"
monitor.handle(exc)
verify(logger).log(
Level.SEVERE,
"The 'qux' service " +
Seq("user", "tweet").mkString(" on behalf of ") +
" threw an exception",
exc
)
}
test("logs IOExceptions at Level.FINE") {
val logger = mock[Logger]
val ioEx = new IOException("hi")
val monitor = new SourceTrackingMonitor(logger, "umm")
monitor.handle(ioEx)
verify(logger).log(mockitoEq(Level.FINE), any(), mockitoEq(ioEx))
}
test("logs Failure.rejected at Level.FINE") {
val logger = mock[Logger]
val monitor = new SourceTrackingMonitor(logger, "umm")
val rejected = Failure.rejected("try again")
monitor.handle(rejected)
verify(logger).log(mockitoEq(Level.FINE), any(), mockitoEq(rejected))
verify(logger, never()).log(mockitoEq(Level.WARNING), any(), mockitoEq(rejected))
}
}
示例3: RefcountedServiceTest
//设置package包名称以及导入依赖的类
package com.twitter.finagle.service
import com.twitter.util._
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito.{times, verify, when}
import org.mockito.{Matchers, Mockito}
import org.mockito.Matchers._
import com.twitter.finagle.Service
@RunWith(classOf[JUnitRunner])
class RefcountedServiceTest extends FunSuite with MockitoSugar {
class PoolServiceWrapperHelper {
val service = mock[Service[Any, Any]]
when(service.close(any)) thenReturn Future.Done
val promise = new Promise[Any]
when(service(Matchers.any)) thenReturn promise
val wrapper = Mockito.spy(new RefcountedService[Any, Any](service))
}
test("PoolServiceWrapper should call release() immediately when no requests have been made") {
val h = new PoolServiceWrapperHelper
import h._
verify(service, times(0)).close(any)
wrapper.close()
verify(service).close(any)
}
test("PoolServiceWrapper should call release() after pending request finishes") {
val h = new PoolServiceWrapperHelper
import h._
val f = wrapper(123)
assert(!f.isDefined)
verify(service)(123)
wrapper.close()
verify(service, times(0)).close(any)
promise() = Return(123)
verify(service).close(any)
assert(f.isDefined)
assert(Await.result(f) == 123)
}
}
示例4: ActorEndpointPathTest
//设置package包名称以及导入依赖的类
package akka.camel.internal.component
import org.scalatest.mock.MockitoSugar
import org.scalatest.Matchers
import akka.camel.TestSupport.SharedCamelSystem
import org.scalatest.WordSpec
import akka.actor.{ Actor, Props }
class ActorEndpointPathTest extends WordSpec with SharedCamelSystem with Matchers with MockitoSugar {
def find(path: String) = ActorEndpointPath.fromCamelPath(path).findActorIn(system)
"findActorIn returns Some(actor ref) if actor exists" in {
val path = system.actorOf(Props(new Actor { def receive = { case _ ? } }), "knownactor").path
find(path.toString) should be('defined)
}
"findActorIn returns None" when {
"non existing valid path" in { find("akka://system/user/unknownactor") should be(None) }
}
"fromCamelPath throws IllegalArgumentException" when {
"invalid path" in {
intercept[IllegalArgumentException] {
find("invalidpath")
}
}
}
}
示例5: RoundCompleteCountdownUpdaterTest
//设置package包名称以及导入依赖的类
package net.xylophones.planetoid.game.logic
import net.xylophones.planetoid.game.logic.ModelTestObjectMother._
import net.xylophones.planetoid.game.model.{GamePhysics, GameEvent, RoundCountdownTimer, GameModel}
import org.junit.runner.RunWith
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, FunSuite}
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class RoundCompleteCountdownUpdaterTest extends FunSuite with Matchers with MockitoSugar {
val currentTimeSource = mock[CurrentTimeSource]
val underTest = new RoundCompleteCountdownUpdater(currentTimeSource)
test("counter gets decremented when exists") {
// given
val model = GameModel(createDummyPlanet(), createDummyPlayers(), roundEndTimer = Some(RoundCountdownTimer(0, 1000, 600)))
when(currentTimeSource.currentTime()).thenReturn(1599)
// when
val result = underTest.update(resultFromModel(model), new GamePhysics(), null)
// then
result.model.roundEndTimer.get.remainingTimeMs shouldBe 1
}
}
示例6: PersonControllerSpec
//设置package包名称以及导入依赖的类
package controllers
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfter, FunSpec}
import play.api.mvc.Results
import play.api.test.FakeRequest
import play.api.test.Helpers._
class PersonControllerSpec extends FunSpec with BeforeAndAfter with Results with MockitoSugar {
var controller: PersonController = _
before {
controller = new PersonController
}
describe("#index") {
it("should return OK with 200") {
val request = FakeRequest("GET", "/person/1")
val response = call(controller.get(1), request)
assert(status(response) === OK)
}
}
}
示例7: SearchControllerTest
//设置package包名称以及导入依赖的类
package controllers
import model.{Runway, Airport, Country, SearchResult}
import org.jsoup.Jsoup
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, FunSpec}
import play.api.test.FakeRequest
import services.SearchService
import org.mockito.Mockito._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
class SearchControllerTest extends FunSpec with Matchers with MockitoSugar with ScalaFutures{
describe("Search Controller"){
it("should generate search results page for given search term"){
new Setup {
when(mockSearchService.searchCountriesByNameOrCountryCode("aus")).thenReturn(Future(expectedSearchResult))
val response = searchController.searchByCountry("aus")(FakeRequest()).futureValue
response.header.status should be(200)
expectedFirstRow should be("Australia AUS Melbourne Airport small CONCRETE 1")
}
}
}
trait Setup{
val mockSearchService = mock[SearchService]
val searchController = new SearchController(mockSearchService)
val expectedSearchResult: Vector[SearchResult] = Vector(SearchResult(Country("Australia","AUS"),Airport("Melbourne Airport","small"),Runway("CONCRETE",1)))
val expectedFirstRow = Jsoup.parse(views.html.search_results(expectedSearchResult.toList).body).select("table > tbody > tr:nth-child(1) td").text()
}
}
示例8: ReportsControllerTest
//设置package包名称以及导入依赖的类
package controllers
import model._
import org.jsoup.Jsoup
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FunSpec, Matchers}
import play.api.test.FakeRequest
import services.ReportService
import org.mockito.Mockito._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class ReportsControllerTest extends FunSpec with Matchers with MockitoSugar with ScalaFutures{
describe("Reports Controller"){
it("should display country name and count of airports in country"){
new Setup {
val response = reportController.getCountriesWithHighestNoOfAirports(FakeRequest()).futureValue
response.header.status should be(200)
val expectedFirstRow = Jsoup.parse(views.html.report("Some Title",expectedSearchResult.toList).body).select("table > tbody > tr:nth-child(1) td").text()
expectedFirstRow should be("Australia 100")
}
}
}
trait Setup{
val mockReportService = mock[ReportService]
val reportController = new ReportsController(mockReportService)
val expectedSearchResult: Vector[CountryReport] = Vector(CountryReport(Country("Australia","AUS"),100))
when(mockReportService.findCountriesWithHighestNoOfAirports).thenReturn(Future(expectedSearchResult))
}
}
示例9: PlayWSReactiveInfluxDbSpec
//设置package包名称以及导入依赖的类
package com.pygmalios.reactiveinflux.impl
import java.net.URI
import com.pygmalios.reactiveinflux.ReactiveInfluxDbName
import com.pygmalios.reactiveinflux.ReactiveInfluxCore
import com.pygmalios.reactiveinflux.command.write._
import org.junit.runner.RunWith
import org.mockito.Mockito._
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
@RunWith(classOf[JUnitRunner])
class PlayWSReactiveInfluxDbSpec extends FlatSpec with MockitoSugar {
behavior of "write of single point"
it should "create WriteCommand and execute it" in new TestScope {
// Execute
db.write(PointSpec.point1)
// Verify
verify(core).execute(new WriteCommand(
baseUri = uri,
dbName = dbName,
points = Seq(PointSpec.point1),
params = WriteParameters()
))
}
behavior of "write of multiple points"
it should "create WriteCommand and execute it" in new TestScope {
val writeCommand = new WriteCommand(
baseUri = uri,
dbName = dbName,
points = Seq(PointSpec.point1, PointSpec.point2),
params = WriteParameters(
retentionPolicy = Some("x"),
precision = Some(Minute),
consistency = Some(All)
)
)
// Execute
db.write(writeCommand.points, writeCommand.params)
// Verify
verify(core).execute(writeCommand)
}
private class TestScope {
val dbName = ReactiveInfluxDbName("db")
val core = mock[ReactiveInfluxCore]
val config = mock[DefaultReactiveInfluxConfig]
val uri = new URI("http://whatever/")
when(config.url).thenReturn(uri)
when(core.config).thenReturn(config)
val db = new PlayWSReactiveInfluxDb(dbName, core)
}
}
示例10: ServiceSpec
//设置package包名称以及导入依赖的类
package service
import models._
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.cache.CacheApi
import services._
class ServiceSpec extends PlaySpec with MockitoSugar {
"UserService" should {
"set list" in {
val cacheService = mock[CacheTrait]
val cache = mock[CacheApi]
cacheService.setCache("kunal", SignUp("", "", "", "", "", "", "", false, false))
when(cache.get[SignUp]("kunal")) thenReturn (Option(SignUp("", "", "", "", "", "", "", false, false)))
}
"get list" in {
val cacheService = mock[CacheTrait]
val cache = mock[CacheApi]
cache.set("kunal", SignUp("", "", "", "", "", "", "", false, false))
when(cacheService.getCache("kunal")) thenReturn (Option(SignUp("", "", "", "", "", "", "", false, false)))
}
"remove list" in {
val cacheService = mock[CacheTrait]
val cache = mock[CacheApi]
cache.set("kunal", SignUp("kunal", "", "", "", "", "", "", false, false))
cacheService.removeFromCache("kunal")
when(cache.get("kunal")) thenReturn (None)
}
}
}
示例11: InitDummyTracksTest
//设置package包名称以及导入依赖的类
package services.dummytracks
import java.io.File
import java.util.UUID
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import models.TrackPoint
import org.mockito.Matchers._
import org.mockito.Mockito._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}
import services.{MultiFormatParser, TrackServiceImpl}
import scala.concurrent.ExecutionContext.Implicits.global
class InitDummyTracksTest extends FlatSpec
with Matchers
with ScalaFutures
with MockitoSugar {
implicit val sys = ActorSystem()
implicit val mat = ActorMaterializer()
val someId = UUID.randomUUID()
"Init track" should "load all 3 device id's into knownDummyUuids" in {
val hashSetMock = mock[scala.collection.mutable.HashSet[UUID]]
val trackService = new TrackServiceImpl[TrackPoint] {
override val knownDummyUuids = hashSetMock
}
val classUnderTest = new LoadInitTracks(trackService)
val trackPointIterator = MultiFormatParser.parse(new File("./test/services/dummytracks/minimal.gpx"))
classUnderTest.loadDummyTrack(trackPointIterator, someId)
verify(trackService.knownDummyUuids, times(3)).+=(any())
}
}
示例12: FrontendFileParserTest
//设置package包名称以及导入依赖的类
package services.parser
import java.io.{File, FileInputStream}
import io.github.karols.units.SI.Short._
import io.github.karols.units._
import models.TrackPoint
import models.TrackPoint.{Annotation, AnnotationValue}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}
class FrontendFileParserTest extends FlatSpec
with Matchers
with ScalaFutures
with MockitoSugar {
val expectedResultsMinimalFPS = List(
TrackPoint(13.210308635607362, 52.50886609777808, 1639.of[ms], None, List(), List(), List(), List(), List(Annotation(AnnotationValue withName "START_JIBE", 1639.of[ms]))),
TrackPoint(13.21028558537364, 52.508917981758714, 1640.of[ms], None, List(), List(), List(), List(), List(Annotation(AnnotationValue withName "MID_JIBE", 1640.of[ms]))),
TrackPoint(13.210270497947931, 52.508938098326325, 1641.of[ms], None, List(), List(), List(), List(), List(Annotation(AnnotationValue withName "END_JIBE", 1641.of[ms])))
)
"A parsed minimal fps file with three Trackpoint elements" should "contain three TrackPoint objects" in {
val fileInputStream = new FileInputStream(new File("./test/services/parser/testfiles/frontendFile.fps"))
val trackPoints = FrontendFileParser.parse(fileInputStream)
trackPoints should have length 3
}
it should "contain the expected TrackPoints" in {
val fileInputStream = new FileInputStream(new File("./test/services/parser/testfiles/frontendFile.fps"))
val trackPoints = FrontendFileParser.parse(fileInputStream)
trackPoints.toList should be(expectedResultsMinimalFPS)
}
}
示例13: CGPSFileParserTest
//设置package包名称以及导入依赖的类
package services.parser
import java.io.{File, FileInputStream}
import models.TrackPoint
import models.TrackPoint.{Accelerometer, Annotation, AnnotationValue, Compass, GpsMeta, Orientation}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FlatSpec, Matchers}
import io.github.karols.units.SI.Short._
import io.github.karols.units._
import models.UnitHelper._
import services.CustomFormatParser
class CGPSFileParserTest extends FlatSpec
with Matchers
with ScalaFutures
with MockitoSugar {
val expectedResultsMinimalAndroidAppFile = List(
TrackPoint(52.518734, 13.321354, 1475681027180L.of[ms], Some(100.0), Seq(GpsMeta(7.0, 0, 0.of[ms])), Seq(Compass(153.6848, 931)), Seq(Accelerometer(-1.2443863.of[m / (s ^ _2)], 4.5406036.of[m / (s ^ _2)], 13.64695.of[m / (s ^ _2)], 931.of[ms])), Seq(Orientation(153.6848, -18.332338, 5.2100616, 931.of[ms])), List(Annotation(AnnotationValue withName "START_JIBE", 11806.of[ms]))),
TrackPoint(52.518574, 13.321948, 1475681046174L.of[ms], Some(84.0), Seq(GpsMeta(9.0, 0, 0.of[ms])), Seq(Compass(170.18939, 280)), Seq(Accelerometer(-0.48123455.of[m / (s ^ _2)], 2.4582467.of[m / (s ^ _2)], 9.826403.of[m / (s ^ _2)], 280.of[ms])), Seq(Orientation(170.18939, -14.029127, 2.8037417, 280.of[ms])), List()),
TrackPoint(52.518394, 13.321941, 1475681056187L.of[ms], Some(92.0), Seq(GpsMeta(9.0, 0, 0.of[ms])), Seq(Compass(156.7807, 1018)), Seq(Accelerometer(1.7262194.of[m / (s ^ _2)], 4.995502.of[m / (s ^ _2)], 12.195465.of[m / (s ^ _2)], 1018.of[ms])), Seq(Orientation(156.7807, -22.076334, -8.056468, 1018.of[ms])), List())
)
"A parsed minimal CustomFormatFile file with three Trackpoint elements" should "contain three TrackPoint objects" in {
val fileInputStream = new FileInputStream(new File("./test/services/parser/testfiles/androidTestFile.json"))
val trackPoints = CustomFormatParser.parse(fileInputStream)
trackPoints should have length 3
}
it should "contain the expected TrackPoints" in {
val fileInputStream = new FileInputStream(new File("./test/services/parser/testfiles/androidTestFile.json"))
val trackPoints = CustomFormatParser.parse(fileInputStream)
trackPoints.toList should be(expectedResultsMinimalAndroidAppFile)
}
}
示例14: NetworkTest
//设置package包名称以及导入依赖的类
package se.andrisak.backprop.algo
import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}
import scala.util.Random
class NetworkTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
val RANDOM_VALUE = 0.2
val INPUT_LAYER_NEURON_COUNT = 1
val HIDDEN_LAYER_NEURON_COUNT = 1
val INPUT = 0.528593
val random = mock[Random]
when(random.nextDouble()).thenReturn(RANDOM_VALUE)
test("test that clearInput clears all node input") {
val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
network.getInputLayer.neurons.head.addInput(0.534543)
network.getHiddenLayer.neurons.head.addInput(0.6854543)
network.clearInputs()
network.getInputLayer.neurons.head.getInput should equal(0.0)
network.getHiddenLayer.neurons.head.getInput should equal(0.0)
}
test("init of input layer should add the input to input neurons") {
val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
network.initInputLayer(List(INPUT))
network.getInputLayer.neurons.head.getInput should equal(INPUT)
}
test("adding more input values than input neurons should throw an exception") {
val network = new Network(INPUT_LAYER_NEURON_COUNT, HIDDEN_LAYER_NEURON_COUNT, random)
intercept[IllegalArgumentException] {
network.initInputLayer(List(INPUT, INPUT))
}
}
}
示例15: NeuronTest
//设置package包名称以及导入依赖的类
package se.andrisak.backprop.algo
import org.mockito.Mockito.when
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfterEach, FunSuite, Matchers}
import scala.util.Random
class NeuronTest extends FunSuite with BeforeAndAfterEach with Matchers with MockitoSugar {
val NEURON_NAME = "neuron"
val NEURON_NAME2 = "neuron2"
val RANDOM_VALUE = 0.53
val random = mock[Random]
when(random.nextDouble()).thenReturn(RANDOM_VALUE)
val neuron = new Neuron(NEURON_NAME, random)
test("input should be stored and be cleared") {
val input = 0.543
neuron.addInput(input)
neuron.getInput should equal (input)
neuron.clearInput()
neuron.getInput should equal (0)
}
test("neurons should be connected with a ForwardLink") {
val neuron2 = new Neuron(NEURON_NAME2, random)
neuron.connectToNeuronsInLayer(List(neuron2))
val link = neuron.getLinkTo(neuron2)
link.to should equal(neuron2)
link.weight should equal(RANDOM_VALUE)
link should equal(neuron.getNextLayerLinks.head)
}
test("neurons should be connected with a ReverseLink") {
val neuron2 = new Neuron(NEURON_NAME2, random)
neuron.connectToNeuronsInPreviousLayer(List(neuron2))
neuron.getPreviousLayerNeurons.head should equal(neuron2)
}
test("test the sigmoid computation") {
neuron.output should equal(0.5)
}
}