springboot~openfeign從JSON檔案讀取資料
阿新 • • 發佈:2018-12-30
對於openfeign來說,幫助我們解決了服務端呼叫服務端的問題,你不需要關心服務端的URI,只需要知道它在eureka裡的服務名稱即可,同時你與服務端確定了服務方法的引數和返回值之後,我們可以在單元測試時mock這些服務端方法即可,真正做到了單元測試,而不需要與外界資源進行互動。
今天主要說一下在openfeign裡讀取JSON檔案的問題,我們將測試所需要的資料儲存到檔案裡,在修改時關注點比較單純。
JSON幫助類,主要使用了objectMapper這個物件
/** * 將json轉換為物件. * * @param 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("讀取json失敗:" + path, e); } } /** * 將json陣列轉換為物件列表. * * @parampath 檔案路徑 */ 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("讀取json失敗:" + path, e); } }
在Mock型別中,可以使用這個方法讀JSON檔案的內容
@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)); } }
上面程式碼主要在模擬了ServiceClient物件裡的del方法,有三個字元型輸入引數,返回值從JSON檔案讀取,在單元測試裡,直接注入的是ServiceClientMock物件,我們
可以從@Profile註解裡看到,它執行在integTest環境中,在生產環境裡,將使用真正的服務。
感謝各位閱讀!