How would you use Akka HTTP’s testing facilities to create unit tests and integration tests for a server-side application?

To create unit tests and integration tests for a server-side application using Akka HTTP’s testing facilities, follow these steps :

1. Add dependencies : Include “akka-http-testkit” in your build configuration to access the required libraries.

2. Unit Testing : For testing individual routes, use the RouteTest trait which provides methods like Get, Post, etc., to send requests to the route. Use assertions with the check method to verify responses.

Example :
class MyRoutesSpec extends WordSpec with Matchers with ScalatestRouteTest {
  val myRoutes = new MyRoutes().routes
  "MyRoutes" should {
    "return a greeting" in {
      Get("/greet") ~> myRoutes ~> check {
        responseAs[String] shouldEqual "Hello!"
      }
    }
  }
}?

3. Integration Testing : To test the entire server, use HttpApp or HttpServerTest. Start the server before tests and stop it after completion. Send requests using an HTTP client like Http() and validate responses.

Example :
class MyServerSpec extends WordSpec with Matchers with BeforeAndAfterAll {
  val server = new MyServer()
  implicit val system = ActorSystem("test-system")
  override def beforeAll(): Unit = server.start()
  override def afterAll(): Unit = server.stop()
  "MyServer" should {
    "return a greeting" in {
      Http().singleRequest(HttpRequest(uri = "http://localhost:8080/greet")).map { response =>
        response.status shouldEqual StatusCodes.OK
        Unmarshal(response.entity).to[String].map(_ shouldEqual "Hello!")
      }
    }
  }
}?