|
| 1 | +package com.github.binarywang.wxpay.testbase; |
| 2 | + |
| 3 | +import com.github.binarywang.wxpay.config.WxPayConfig; |
| 4 | +import com.github.binarywang.wxpay.service.WxPayService; |
| 5 | +import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl; |
| 6 | +import com.google.inject.Binder; |
| 7 | +import com.google.inject.Module; |
| 8 | +import com.thoughtworks.xstream.XStream; |
| 9 | +import me.chanjar.weixin.common.error.WxRuntimeException; |
| 10 | +import me.chanjar.weixin.common.util.xml.XStreamInitializer; |
| 11 | +import org.apache.http.HttpRequestInterceptor; |
| 12 | +import org.slf4j.Logger; |
| 13 | +import org.slf4j.LoggerFactory; |
| 14 | + |
| 15 | +import java.io.IOException; |
| 16 | +import java.io.InputStream; |
| 17 | + |
| 18 | +/** |
| 19 | + * The type Api test module. |
| 20 | + */ |
| 21 | +public class CustomizedApiTestModule implements Module { |
| 22 | + private final Logger log = LoggerFactory.getLogger(this.getClass()); |
| 23 | + private static final String TEST_CONFIG_XML = "test-config.xml"; |
| 24 | + |
| 25 | + @Override |
| 26 | + public void configure(Binder binder) { |
| 27 | + try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(TEST_CONFIG_XML)) { |
| 28 | + if (inputStream == null) { |
| 29 | + throw new WxRuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到,请参照test-config-sample.xml文件生成"); |
| 30 | + } |
| 31 | + |
| 32 | + XmlWxPayConfig config = this.fromXml(XmlWxPayConfig.class, inputStream); |
| 33 | + config.setIfSaveApiData(true); |
| 34 | + |
| 35 | + config.setApiV3HttpClientBuilderCustomizer((builder) -> { |
| 36 | + builder.addInterceptorLast((HttpRequestInterceptor) (r, c) -> System.out.println("--------> V3 HttpRequestInterceptor ...")); |
| 37 | + }); |
| 38 | + |
| 39 | + config.setHttpClientBuilderCustomizer((builder) -> { |
| 40 | + builder.addInterceptorLast((HttpRequestInterceptor) (r, c) -> System.out.println("--------> HttpRequestInterceptor ...")); |
| 41 | + }); |
| 42 | + |
| 43 | + WxPayService wxService = new WxPayServiceImpl(); |
| 44 | + wxService.setConfig(config); |
| 45 | + |
| 46 | + binder.bind(WxPayService.class).toInstance(wxService); |
| 47 | + binder.bind(WxPayConfig.class).toInstance(config); |
| 48 | + } catch (IOException e) { |
| 49 | + this.log.error(e.getMessage(), e); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + @SuppressWarnings("unchecked") |
| 54 | + private <T> T fromXml(Class<T> clazz, InputStream is) { |
| 55 | + XStream xstream = XStreamInitializer.getInstance(); |
| 56 | + xstream.alias("xml", clazz); |
| 57 | + xstream.processAnnotations(clazz); |
| 58 | + return (T) xstream.fromXML(is); |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments