Students who are not clear about openfeign can refer to my article: springboot~openfeign says goodbye to httpClient from now on
For openfeign, it helps us solve the problem of server calling server. You don’t need to care about the URI of the server, you just need to know its service name in eureka. At the same time, after you determine the parameters and return value of the service method with the server, we can mock these server methods during unit testing, and truly achieve unit testing without interacting with external resources.
Today, we will mainly talk about the problem of reading JSON files in openfeign. We store the data required for the test into the file, and the focus is relatively simple when modifying it.
JSON help class mainly uses objectMapper object
/** * Convert json to an object. * * @param path File path*/ public <T> T fromJson(String path, Class<T> cls) { try { return objectMapper.readValue(this.fromResource(path, Charsets.UTF_8), cls); } catch (Exception e) { throw new IllegalStateException("Read json failed:" + path, e); } } /** * Convert json array to object list. * * @param path File path*/ public <T> List<T> listFromJson(String path, TypeReference typeReference) { try { return objectMapper.readValue(fromResource(path, Charsets.UTF_8), typeReference); } catch (Exception e) { throw new IllegalStateException("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() { AccountClient client = 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. It has three character input parameters, and the return value is read from the JSON file. In the unit test, the ServiceClientMock object is directly injected.
As you can see from the @Profile annotation, it runs in the integTest environment, and in the production environment, it will use real services.
Summarize
The above is the springboot openfeign reading data from JSON files introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!