A lightweight java unit test library for mocking thrift service
- Init thrift mock server without any pre-define thrift idl, only a port is needed
- Dynamic binding thrift interface to its response
- Configurable response delays
- Support binding different interfaces from different thrift service to one server
- Embedded with junit4
working with junit
<dependency>
<groupId>com.didiglobal.thriftmock</groupId>
<artifactId>thrift-mock-server4junit</artifactId>
<version>1.0.0</version>
</dependency>
working without junit
<dependency>
<groupId>com.didiglobal.thriftmock</groupId>
<artifactId>thrift-mock-server</artifactId>
<version>1.0.0</version>
</dependency>
thrift test source
<dependency>
<groupId>com.didiglobal.thriftmock</groupId>
<artifactId>thrift-mock-server</artifactId>
<version>1.0.0</version>
</dependency>
//working without junit, starting a non-blocking server
ThriftMockServer server = new ThriftMockServer(9999);
Thread t = new Thread(server::start);
t.start();
//working with junit
@Rule
public ThriftMockServer server = new ThriftMockServer(9999);
If you have a thrift file like this:
namespace java com.xiaoju.ddpay.thriftmock.server
struct Request{
1:optional string msg,
}
struct Response{
1:required i32 code,
2:required string responseMsg,
}
service HelloService {
Response sayHello(1:required Request request);
}
service ByeService {
Response sayBye(1:required Request request);
}
//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);
//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);
//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");
- thrift-mock don't support aysnc call yet, but we will support it in next release version.
Welcome to contribute by creating issues or sending pull requests. See Contributing Guide for guidelines.
thrift-mock is licensed under the Apache License 2.0. See the LICENSE file.
This is not an official Didi product (experimental or otherwise), it is just code that happens to be owned by Didi.