Openfeign not clear to the classmate can first read me this article: Springboot~openfeign and HttpClient Say goodbye
For Openfeign, to help us solve the service side of the call server problem, you do not need to care about the service side of the URI, only need to know its service name in the Eureka, and you and the server to determine the service method parameters and return value, We can mock these server-side methods during unit testing, and really do unit testing without having to interact with external resources.
Today the main point is to read the JSON file in the openfeign problem, we will test the required data stored in the file, the changes in the focus is relatively simple.
The JSON helper class, which uses the Objectmapper object primarily
/*** Convert JSON to an object. * * @paramPath file Paths*/ Public<T> T Fromjson (String path, class<t>CLS) { Try { returnObjectmapper.readvalue ( This. Fromresource (Path, charsets.utf_8), CLS); } Catch(Exception e) {Throw NewIllegalStateException ("Read JSON failed:" +path, E); } } /*** Converts a JSON array to a list of objects. * * @paramPath file Paths*/ Public<T> list<t>Listfromjson (String path, typereference typereference) {Try { returnObjectmapper.readvalue (Fromresource (Path, charsets.utf_8), typereference); } Catch(Exception e) {Throw NewIllegalStateException ("Read JSON failed:" +path, E); } }
In the mock type, you can use this method to read the contents of the JSON file
@Configuration @profile ("Integtest") Public class Serviceclientmock { @Bean public serviceclient registerserviceclient () { = mock (accountclient. Class); When (Client.del ( anystring (), anystring (), anystring (), Anymap ())). Thenreturn (Fromjson ( "Order/orders.json", Map. class )); }}
The above code mainly simulates the Del method in the ServiceClient object, there are three character input parameters, the return value is read from the JSON file, in the unit test, directly injected is the Serviceclientmock object, we
As you can see from the @profile annotations, it runs in the integtest environment, where real services are used in the production environment.
Thank you for reading!
Springboot~openfeign reading data from a JSON file