Local mock 1 is usually used for service downgrade, such as a verification service, the client does not throw an exception when the service provider hangs up all the time, but returns the authorization failed through the Mock data.
Configured in the spring configuration file as follows:
or
Mock implementation in the project 2:
If the service consumer often needs try-catch
to catch exceptions, such as:
Consider changing to Mock implementation and return null in Mock implementation. If you just want to simply ignore the exception, 2.0.11
version or later version is available:
return
can be used to return an object’s string representation as the mocked return value. The legal values incude:
null
true
false
throw
can be used to throw an exception object as the mocked return value.
Throw a default RPCException when invocation gets wrong:
Throw a specified exception when invocation gets wrong:
Since 2.6.6
and above, it is possible to use fail:
and force:
in Spring’s XML configuration to define mock behavior. force:
means the mocked value is forced to use no matter the invocation gets wrong or not, in fact, the remote invocation will not happen at all. fail:
is consistent with the default behavior, that is, mock happens only when invocation gets wrong. Futhermore, both force:
and fail:
can be used together with throw
or return
to define the mock behavior further.
Force to return the specified value:
Force to throw the specified exception:
Mock behavior can be specified on the method level. Assume there are a couple of methods on com.foo.BarService
, we can specify the mock behavior for one particular method only, say sayHello()
. In the example below, “fake” is forced to return everytime when sayHello()
is called, but other methods will not be effected:
Mock is a subset of the Stub. If you use Stub, you may need to rely on the RpcException class. If you use Mock, you do not need to rely on RpcException, when throwing RpcException, it will callback Mock implementation class. ↩︎
BarServiceMock implements BarService and has a no-argument constructor. ↩︎