1 package top.infra.test.contract; 2 3 import org.junit.rules.TestRule; 4 import org.junit.runner.Description; 5 import org.junit.runners.model.MultipleFailureException; 6 import org.junit.runners.model.Statement; 7 8 import java.util.ArrayList; 9 import java.util.List; 10 11 public class ContractRule implements TestRule { 12 13 private static final String EUREKA_CLIENT_ENABLED = "eureka.client.enabled"; 14 private static final String SPRING_CLOUD_CONFIG_DISCOVERY_ENABLED = "spring.cloud.config.discovery.enabled"; 15 private static final String SPRING_CLOUD_CONFIG_FAILFAST = "spring.cloud.config.failFast"; 16 private String eurekaClientEnabled = null; 17 private String springCloudConfigDiscoveryEnabled = null; 18 private String springCloudConfigFailFast = null; 19 20 @Override 21 public Statement apply(final Statement base, final Description description) { 22 return new Statement() { 23 24 @Override 25 public void evaluate() throws Throwable { 26 27 List<Throwable> errors = new ArrayList<>(); 28 29 try { 30 starting(description); 31 base.evaluate(); 32 succeeded(description); 33 } catch (Throwable e) { 34 errors.add(e); 35 failed(e, description); 36 } finally { 37 finished(description); 38 } 39 40 MultipleFailureException.assertEmpty(errors); 41 } 42 }; 43 } 44 45 protected void starting(Description description) { 46 this.backupProperties(); 47 48 this.setProperties(); 49 } 50 51 protected void succeeded(Description description) { 52 } 53 54 protected void failed(Throwable e, Description description) { 55 } 56 57 protected void finished(Description description) { 58 this.restoreProperties(); 59 } 60 61 private void backupProperties() { 62 this.eurekaClientEnabled = System.getProperty(EUREKA_CLIENT_ENABLED); 63 this.springCloudConfigDiscoveryEnabled = System.getProperty(SPRING_CLOUD_CONFIG_DISCOVERY_ENABLED); 64 this.springCloudConfigFailFast = System.getProperty(SPRING_CLOUD_CONFIG_FAILFAST); 65 } 66 67 private void restoreProperties() { 68 if (this.eurekaClientEnabled != null) { 69 System.setProperty(EUREKA_CLIENT_ENABLED, this.eurekaClientEnabled); 70 } else { 71 System.getProperties().remove(EUREKA_CLIENT_ENABLED); 72 } 73 74 if (this.springCloudConfigDiscoveryEnabled != null) { 75 System.setProperty(SPRING_CLOUD_CONFIG_DISCOVERY_ENABLED, this.springCloudConfigDiscoveryEnabled); 76 } else { 77 System.getProperties().remove(SPRING_CLOUD_CONFIG_DISCOVERY_ENABLED); 78 } 79 80 if (this.springCloudConfigFailFast != null) { 81 System.setProperty(SPRING_CLOUD_CONFIG_FAILFAST, this.springCloudConfigFailFast); 82 } else { 83 System.getProperties().remove(SPRING_CLOUD_CONFIG_FAILFAST); 84 } 85 } 86 87 private void setProperties() { 88 System.setProperty(EUREKA_CLIENT_ENABLED, "false"); 89 System.setProperty(SPRING_CLOUD_CONFIG_DISCOVERY_ENABLED, "false"); 90 System.setProperty(SPRING_CLOUD_CONFIG_FAILFAST, "false"); 91 } 92 }