All Projects → orhanobut → Mockwebserverplus

orhanobut / Mockwebserverplus

Licence: apache-2.0
✔️ OkHttp mockwebserver with fixtures extension

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Mockwebserverplus

main
Mocks Server monorepo
Stars: ✭ 109 (+25.29%)
Mutual labels:  fixtures, testing-tools
Beanmother
A library for setting up Java objects as test data.
Stars: ✭ 102 (+17.24%)
Mutual labels:  testing-tools, fixtures
Gunit
xUnit-style test fixture adapter for go test
Stars: ✭ 94 (+8.05%)
Mutual labels:  testing-tools, fixtures
Pytest Mimesis
Mimesis integration with the pytest test runner. This plugin provider useful fixtures based on providers from Mimesis.
Stars: ✭ 46 (-47.13%)
Mutual labels:  testing-tools, fixtures
Awesome K6
A curated list of resources on automated load- and performance testing using k6 🗻
Stars: ✭ 78 (-10.34%)
Mutual labels:  testing-tools
Wp Cli Fixtures
Easily generate custom fake data for WordPress
Stars: ✭ 65 (-25.29%)
Mutual labels:  fixtures
Smoke
Runs tests against anything, using command-line arguments, STDIN, STDOUT and STDERR.
Stars: ✭ 60 (-31.03%)
Mutual labels:  testing-tools
Junitparser
Parses JUnit/xUnit Result XML files with ease
Stars: ✭ 58 (-33.33%)
Mutual labels:  testing-tools
Snapper
Bringing Jest-esque Snapshot testing to C#
Stars: ✭ 85 (-2.3%)
Mutual labels:  testing-tools
Testcl
when you don't have the balls to test your F5 BIG-IP iRules directly in production
Stars: ✭ 79 (-9.2%)
Mutual labels:  testing-tools
Wedgetail
Time your functions in your tests
Stars: ✭ 74 (-14.94%)
Mutual labels:  testing-tools
Meissa
Cross-platform Distributed Test Runner. Executes tests in parallel, time balanced on multiple machines.
Stars: ✭ 66 (-24.14%)
Mutual labels:  testing-tools
Testdouble.js
A minimal test double library for TDD with JavaScript
Stars: ✭ 1,214 (+1295.4%)
Mutual labels:  testing-tools
Qtools
QTools collection of open source tools for embedded systems development on Windows, Linux and MacOS
Stars: ✭ 64 (-26.44%)
Mutual labels:  testing-tools
Testcafe
A Node.js tool to automate end-to-end web testing.
Stars: ✭ 9,176 (+10447.13%)
Mutual labels:  testing-tools
Phpspec Code Coverage
Generate Code Coverage reports for PhpSpec tests
Stars: ✭ 59 (-32.18%)
Mutual labels:  testing-tools
System tester
A Development Tool for creating and managing system tests for Ruby on Rails >= 5.1 Applications
Stars: ✭ 73 (-16.09%)
Mutual labels:  testing-tools
Perftools Runner
Google Performance Tools runner using Puppeteer
Stars: ✭ 79 (-9.2%)
Mutual labels:  testing-tools
Reportportal
Main Repository. Report Portal starts here - see readme below.
Stars: ✭ 1,175 (+1250.57%)
Mutual labels:  testing-tools
Assert
A collection of convenient assertions for Swift testing
Stars: ✭ 69 (-20.69%)
Mutual labels:  testing-tools

mockwebserver +

Issue

MockWebServer is a great tool for mocking network requests/responses. In order to add response, you need to set MockResponse body along with all properties you need

@Rule public MockWebServer server = new MockWebServer();

@Test public void uglyTest() {
  server.enqueue(new MockResponse()
    .setStatusCode(200)
    .setBody({
               "array": [
                 1,
                 2,
                 3
               ],
               "boolean": true,
               "null": null,
               "number": 123,
               "object": {
                 "a": "b",
                 "c": "d",
                 "e": "f"
               },
               "string": "Hello World"
             })
    .addHeader("HeaderKey:HeaderValue")
    .responseDelay(3, SECONDS)
  );
  
  // execute request
  // assert
  // verify
}

Imagine it with huge json responses. It will obscure the method content and will be barely readable.

Solution

In order to make it more readable, you can use fixtures. Move away your response to the fixtures and just reference them. MockWebServerPlus is a wrapper which contains MockWebServer with fixtures feature.

Create a fixture yaml file under resources/fixtures
src
├── test
│   ├── java
│   ├── resources
│   │   ├── fixtures
│   │   │   ├── foo_success.yaml
│   │   │   ├── foo_failure.yaml
statusCode : 200       // as the name says
delay: 0               // delays the response
headers:               // adds to the response
- 'Auth:auth'
- 'key:value'
body: 'common/body_file.json' // can be any path under /fixtures folder
// or inline
body: >                       // can be any text, json, plain etc. Use > letter for scalar text
    {
      "array": [
        1,
        2,
        3
      ],
      "boolean": true,
      "null": null,
      "number": 123,
      "object": {
        "a": "b",
        "c": "d",
        "e": "f"
      },
      "string": "Hello World"
    }

Use the file name to reference it. That's it!

@Rule public MockWebServerPlus server = new MockWebServerPlus();

@Test public void readableTest() {
  server.enqueue("foo_success");
  
  // execute request
  // assert
  // verify
}

Use the generated Fixtures.java to reference your fixtures. Read the Generate Fixtures.java part

server.enqueue(Fixtures.FOO_SUCCESS);

Enqueue multiple response

server.enqueue(Fixtures.FOO_SUCCESS, Fixtures.USER_REGISTER_SUCCESS);

Custom Dispatcher

You may wish to use a custom dispatcher with the mock web server.

Fixtures can be used directly inside a Dispatcher:

new Dispatcher() {
  @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
    return Fixture.parseFrom("simple).toMockResponse();
  }
}

Generate Fixtures.java

You can always use plain text to reference your fixtures.

server.enqueue("foo_success");

but you can also generate Fixtures.java file to have all of them with a task. This will make your code more type-safe. Put the following task into your build.gradle file and execute it when you add/modify your fixture resources.

task generateFixtures(dependsOn: copyTestResources) << {
  def directory = projectDir.path + '/src/test/java'
  new File(directory + '/fixtures').mkdir()
  def path = directory + "/fixtures/Fixtures.java"

  def builder = '' << ''
  builder.append("package fixtures;\n\n")
  builder.append("public class Fixtures {\n\n")
  builder.append("  private Fixtures() {\n")
  builder.append("    //no instance\n")
  builder.append("  }\n\n")

  def resources = android.sourceSets.test.resources.srcDirs.getAt(0)
  if (resources.size() > 0) {
    resources.eachDirMatch("fixtures") { dir ->
      def fixturesFile = dir
      fixturesFile.eachFile(FileType.FILES) { file ->
        if (file.name.endsWith(".yaml")) {
          String fileName = file.name.split('\\.')[0]
          builder.append("  public static final String ")
              .append(fileName.toUpperCase())
              .append(" = ")
              .append('\"')
              .append(fileName)
              .append('\";\n')
        }
      }
    }
  }
  builder.append("}\n")

  new File(path).write(builder.toString())
}

Above solution will generate Fixtures.java when you execute it manually. But you might forget to execute it, you can make it dependent for any task to make it automated. Whenever preBuild is executed, it will also execute this task

preBuild.dependsOn generateFixtures

Install

testCompile 'com.orhanobut:mockwebserverplus:2.0.0'

// This is optional, but in order to be up-to-date with OkHttp changes, you can use the latest version
testCompile 'com.squareup.okhttp3:mockwebserver:3.7.0'  

Other proxy methods

MockWebServerPlus.server()         // returns MockWebServer instance
MockWebServerPlus.takeRequest()    // returns RecordedRequest
MockWebServerPlus.url(String path) // returns url to execute
MockWebServerPlus.setDispatcher(Dispatcher dispatcher)  // any custom dispatcher
MockWebServerPlus.enqueue(SocketPolicy socketPolicy)    // Useful for network errors, such as DISCONNECT etc

Get the fixture object

Fixture fixture = Fixture.parseFrom(Fixtures.SIMPLE);

For non-android modules

For non-android modules, you may need to add the following tasks to copy your resources into classes dir

task copyTestResources(type: Copy) {
  from sourceSets.test.resources
  into sourceSets.test.output.classesDir
}

How it works

Also notice that accessing sourceSets should be without android.

Credits

MockWebServer from Square

License

Copyright 2017 Orhan Obut

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].