//working without junit, blocking server
ThriftMockServer server = new ThriftMockServer(9999);
Thread t = new Thread(server::start);
t.start();
//working without junit, starting a non-blocking server
AsyncThriftMockServer server = new AsyncThriftMockServer(9999);
Thread t = new Thread(server::start);
t.start();
//working with junit
//blocking server
@Rule
public ThriftMockServer server = new ThriftMockServer(9999);
//non-blocking server
@Rule
public AsyncThriftMockServer server = new AsyncThriftMockServer(9999);
//define expect response
Response expectHelloResponse = new Response(200, "hello");
//bind response
server.setExpectReturn("sayHello", expectHelloResponse);
//bind response with specific delay(ms)
server.setExpectReturn("sayHello", expectHelloResponse, 100);
3.2 bind interface to dynamic response
//bind interface to dynamic response
TBase emptyArgs = new HelloService.sayHello_args();
Function<TBase, TBase> returnLogic = (tBase) -> {
HelloService.sayHello_args sayHello_args = (HelloService.sayHello_args)tBase;
if (sayHello_args.getRequest().getMsg().contains("fail")) {
return new Response(500, "fail");
}
return new Response(200, "success");
};
server.setExpectReturn("sayHello", emptyArgs, returnLogic);
3.3 request server
//init a thrift client connect to mock server
TTransport transport = new TSocket("127.0.0.1", 9999);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
HelloService.Iface client = new HelloService.Client(protocol);
//request interface sayHello
Response msg = client.sayHello(request);
//get the expect response
Assert.assertEquals(msg.getCode(), 200);
Assert.assertEquals(msg.getMsg(), "hello");
Todo
make it work like wiremock to test thrift service.
Contributing
Welcome to contribute by creating issues or sending pull requests. See Contributing Guide for guidelines.
License
thrift-mock is licensed under the Apache License 2.0. See the LICENSE file.
Note
This is not an official Didi product (experimental or otherwise), it is just code that happens to be owned by Didi.
thrift-mock
A lightweight java unit test library for mocking thrift service
Requires Java 17 or higher. Tested and supported on Java 17 and Java 21.
Features
Getting Started
1. import maven dependency
working with junit
working without junit
thrift test source
2. start server
3. bind interface with expect response
If you have a thrift file like this:
3.1 bind interface to fixed response
3.2 bind interface to dynamic response
3.3 request server
Todo
Contributing
Welcome to contribute by creating issues or sending pull requests. See Contributing Guide for guidelines.License
thrift-mock is licensed under the Apache License 2.0. See the LICENSE file.
Note
This is not an official Didi product (experimental or otherwise), it is just code that happens to be owned by Didi.