Adapts Java interface created by Retrofit using annotations on declared methods to define response mocks.
implementation 'co.infinum:retromock:1.1.1'
Retromock retromock = new Retromock.Builder()
.retrofit(retrofit)
.build();
Service service = retromock.create(Service.class);
public interface Service {
@Mock
@MockResponse(body = "{\"name\":\"John\", \"surname\":\"Doe\"}")
@GET("/endpoint")
Call<User> getUser();
}
Call<User> = service.getUser();
If you would like to load response from a stream set a default body factory that loads a response stream by a body parameter(response.json
) in annotation.
Retromock retromock = new Retromock.Builder()
.retrofit(retrofit)
.defaultBodyFactory(...)
.build();
public interface Service {
@Mock
@MockResponse(body = "response.json")
@GET("/endpoint")
Call<User> getUser();
}
Retromock retromock = new Retromock.Builder()
.retrofit(retrofit)
.defaultBodyFactory(context.getAssets()::open)
.build();
public interface Service {
@Mock
@MockResponse(body = "retromock/response.json")
@GET("/endpoint")
Call<User> getUser();
}
Save a response body content in file named retromock/response.json
.
If you use Retromock
only in some variants you can exclude files with mock responses from final .apk with configuration similar to:
applicationVariants.all { variant ->
if (variant.buildType.name.contains('production')) {
variant.mergeAssets.doLast {
delete(fileTree(dir: variant.mergeAssets.outputDir, includes: ['**/retromock/*']))
}
}
}
Note: if you set custom default body factory and do not declare a bodyFactory
parameter in @MockResponse
annotation your body factory will be called with value of body
parameter.
That also applies if you don't specificaly set a body
- in that case body
is empty by default.
If you wouldn't like to handle the case of empty body
wrap your default body factory into NonEmptyBodyFactory
class as follows:
Retromock retromock = new Retromock.Builder()
.retrofit(retrofit)
.defaultBodyFactory(new NonEmptyBodyFactory(...))
.build();
For more information please see the full specification.
The library does not require any ProGuard rules.
However, you might need rules for Retrofit and its dependencies.
Copyright 2019 Infinum
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.
Maintained and sponsored by Infinum.