Результат теста простого маршрута распыления: не удалось инициализировать класс spray.http.Uri$

Я новичок в спреях. Я пытаюсь провести тестирование правильно, поэтому я использовал пример, показанный в spary testkit Однако я получаю эту ошибку. любая помощь будет принята с благодарностью:

The service should

Could not initialize class spray.http.Uri$
java.lang.NoClassDefFoundError: Could not initialize class spray.http.Uri$
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:36)
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:34)
    at com.tr.route.EventRouteTester$$anonfun$3$$anonfun$apply$2.apply(EventRouteTester.scala:38)
    at com.tr.route.EventRouteTester$$anonfun$3$$anonfun$apply$2.apply(EventRouteTester.scala:38)

return a 'PONG!' response for GET requests to /ping

Could not initialize class spray.http.Uri$
java.lang.NoClassDefFoundError: Could not initialize class spray.http.Uri$
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:36)
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:34)
    at com.tr.route.EventRouteTester$$anonfun$3$$anonfun$apply$6.apply(EventRouteTester.scala:44)
    at com.tr.route.EventRouteTester$$anonfun$3$$anonfun$apply$6.apply(EventRouteTester.scala:44)

leave GET requests to other paths unhandled

scala/collection/GenTraversableOnce$class
java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce$class
    at spray.http.Uri$Query.<init>(Uri.scala:496)
    at spray.http.Uri$Query$Empty$.<init>(Uri.scala:575)
    at spray.http.Uri$Query$Empty$.<clinit>(Uri.scala)
    at spray.http.parser.UriParser.<init>(UriParser.scala:37)
    at spray.http.Uri$.apply(Uri.scala:231)
    at spray.http.Uri$.apply(Uri.scala:203)
    at spray.http.Uri$.<init>(Uri.scala:194)
    at spray.http.Uri$.<clinit>(Uri.scala)
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:36)
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:34)
    at spray.httpx.RequestBuilding$RequestBuilder.apply(RequestBuilding.scala:33)
    at com.tr.route.EventRouteTester$$anonfun$3$$anonfun$apply$9.apply(EventRouteTester.scala:50)
    at com.tr.route.EventRouteTester$$anonfun$3$$anonfun$apply$9.apply(EventRouteTester.scala:50)
Caused by: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce$class
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    ... 13 more

return a MethodNotAllowed error for PUT requests to the root path

это тестовый класс

class RouteTester extends Specification with Specs2RouteTest with HttpService {
  def actorRefFactory = system // connect the DSL to the test ActorSystem

  val smallRoute =
    get {
      pathSingleSlash {
        complete {
          <html>
            <body>
              <h1>Say hello to <i>spray</i>!</h1>
            </body>
          </html>
        }
      } ~
        path("ping") {
          complete("PONG!")
        }
    }

  "The service" should {

    "return a greeting for GET requests to the root path" in {
      Get() ~> smallRoute ~> check {
        responseAs[String] must contain("Say hello")
      }
    }

    "return a 'PONG!' response for GET requests to /ping" in {
      Get("/ping") ~> smallRoute ~> check {
        responseAs[String] === "PONG!"
      }
    }

    "leave GET requests to other paths unhandled" in {
      Get("/kermit") ~> smallRoute ~> check {
        handled must beFalse
      }
    }

    "return a MethodNotAllowed error for PUT requests to the root path" in {
      Put() ~> sealRoute(smallRoute) ~> check {
        status === MethodNotAllowed
        responseAs[String] === "HTTP method not allowed, supported methods: GET"
      }
    }
  }
}

Я использую maven, это зависимости и версии

  <scala.version>2.11.2</scala.version>
        <spray.version>1.3.1</spray.version>
        <akka.version>2.3.8</akka.version>

      <dependency>
            <groupId>io.spray</groupId>
            <artifactId>spray-can</artifactId>
            <version>${spray.version}</version>
        </dependency>
        <dependency>
            <groupId>io.spray</groupId>
            <artifactId>spray-routing</artifactId>
            <version>${spray.version}</version>
        </dependency>
        <dependency>
            <groupId>io.spray</groupId>
            <artifactId>spray-json_2.11</artifactId>
            <version>${spray.version}</version>
        </dependency>
         <dependency>
            <groupId>io.spray</groupId>
            <artifactId>spray-testkit_2.11</artifactId>
             <version>${spray.version}</version>
        </dependency>

person igx    schedule 05.03.2015    source источник
comment
Похоже, что код запустился, хотя компилировать его не следовало. Каков результат mvn compile?   -  person mirelon    schedule 05.03.2015
comment
@mirelon mvn очистить результаты компиляции - добиться успеха   -  person igx    schedule 05.03.2015
comment
Я понятия не имею, почему классы не найдены, но недавно я прошел через это и в итоге использовал чистый akka-testkit, проверяя передачу сообщений HttpServiceActor (отправленный HttpRequest и ожидаемый HttpResponse). Если вам интересно, я могу поделиться кодом...   -  person mirelon    schedule 05.03.2015
comment
@mirelon конечно, это будет круто. Спасибо !   -  person igx    schedule 05.03.2015
comment
Возможно, это все еще не сработает для вас... но вы можете попробовать. Кажется, что ваша настоящая проблема - это зависимости (maven загружает их в локальный репозиторий, а затем, когда он запускает тест, он не может найти классы) - проверьте свой локальный репозиторий maven, если он содержит зависимости   -  person mirelon    schedule 05.03.2015


Ответы (2)


В последнее время я слишком боролся с различными тесткитами и в итоге использовал чистый Akka TestKit, потому что Spray TestKit заставлял меня разбивать мои HttpServiceActors на отдельные трейты и актеры, что было для меня неприемлемо.

Я могу поделиться некоторым кодом для вдохновения, вы можете попробовать (если кто-то не придет с лучшим ответом):

RestInterface.scala:

import spray.routing.HttpServiceActor

class RestInterface extends HttpServiceActor {
  override def receive: Receive = runRoute(smallRoute)
  val smallRoute =
    get {
      pathSingleSlash {
        complete {
          <html>
            <body>
              <h1>Say hello to <i>spray</i>!</h1>
            </body>
          </html>
        }
      } ~
      path("ping") {
        complete("PONG!")
      }
    }
}

RestInterfaceSpec.scala:

import akka.actor.{Props, ActorSystem}
import akka.testkit.{TestActorRef, ImplicitSender, TestKit}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
import spray.http.HttpResponse
import spray.httpx.RequestBuilding

class RestInterfaceSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with WordSpecLike with Matchers with BeforeAndAfterAll with RequestBuilding with SpecHelper {
  def this() = this(ActorSystem("MySpec"))

  "The service" must {
    "return a response" in {
      val service = TestActorRef[RestInterface]
      service ! Get("/")
      expectMsgType[HttpResponse]
    }
  }
}

SpecHelper.scala:

import akka.actor.ActorSystem
import akka.testkit.TestKit

trait SpecHelper extends BeforeAndAfterAll { this: Suite =>
  implicit val system: ActorSystem

  override def afterAll(): Unit = {
    TestKit.shutdownActorSystem(system)
  }
}
person mirelon    schedule 05.03.2015
comment
Ну, тут тоже не повезло... запускаю свой код и получаю эту ошибку: нужный класс не найден. Это может быть связано с ошибкой в ​​пути выполнения. Отсутствует класс: scala/runtime/AbstractPartialFunction$mcVL$sp java.lang.NoClassDefFoundError: scala/runtime/AbstractPartialFunction$mcVL$sp at java.lang.ClassLoader.defineClass1 (собственный метод)... - person igx; 06.03.2015
comment
Возможно, это будет чисто maven-проблема, взгляните на stackoverflow.com/questions/16420935/, stackoverflow.com/questions/ 18442753/, stackoverflow.com/questions/20689773/casbah -scala-runtime-ошибка - person mirelon; 06.03.2015
comment
Это не похоже на знатока, но, может быть, - person igx; 06.03.2015
comment
Привет, спасибо за подсказку, вы были правы, это была проблема с maven, хотя это больше похоже на версию спрей-модулей. Спасибо, ваш код вдохновил меня, и я использовал ваш подход. Спасибо чувак - person igx; 09.03.2015

решено! Проблема заключалась в том, что зависимости требуют разных версий. т. е. артефакты аэрозольного баллончика и распылительной маршрутизации зависят от scala 2.10, в то время как остальные объявленные зависимости зависят от scala 2.11.

все, что мне нужно было сделать, это изменить зависимости на:

<scalaBinaryVersion>2.11</scalaBinaryVersion>
<dependency>
    <groupId>io.spray</groupId>
    <artifactId>spray-can_${scalaBinaryVersion}</artifactId>

    <version>${spray.version}</version>
</dependency>
<dependency>
    <groupId>io.spray</groupId>
    <artifactId>spray-routing_${scalaBinaryVersion}</artifactId>

    <version>${spray.version}</version>
</dependency>

и проблема решена!

person igx    schedule 06.03.2015
comment
О да, я проглядел. Я использую SBT вместо Maven, и он скрывает это в символе двойного процента: значение"> stackoverflow.com/questions/17461453/ - person mirelon; 09.03.2015