尽管您不一定需要UNIT测试hystrix命令。进行某种春季混合测试仍然有用,我认为在添加注释时点空白接受功能是不正确的。我创建的测试可确保断路器在出现异常时断开。
@RunWith(SpringRunner.class)@SpringBootTestpublic class HystrixProxyServiceTests { @MockBean private MyRepo myRepo; @Autowired private MyService myService; private static final String ID = “1”; @Before public void setup() { resetHystrix(); openCircuitBreakerAfteroneFailingRequest(); } @Test public void circuitBreakerClosedonSuccess() throws IOException, InterruptedException { when(myRepo.findoneById(USER_ID1)) .thenReturn(Optional.of(document.builder().build())); myService.findoneById(USER_ID1); HystrixCircuitBreaker circuitBreaker = getCircuitBreaker(); Assert.assertTrue(circuitBreaker.allowRequest()); verify(myRepo, times(1)).findoneById( any(String.class)); } @Test public void circuitBreakerOpenonException() throws IOException, InterruptedException { when(myRepo.findoneById(ID)) .thenThrow(new RuntimeException()); try { myService.findoneById(ID); } catch (RuntimeException exception) { waitUntilCircuitBreakerOpens(); HystrixCircuitBreaker circuitBreaker = getCircuitBreaker(); Assert.assertFalse(circuitBreaker.allowRequest()); } verify(myRepo, times(1)).findoneById( any(String.class)); } private void waitUntilCircuitBreakerOpens() throws InterruptedException { Thread.sleep(1000); } private void resetHystrix() { Hystrix.reset(); } private void warmUpCircuitBreaker() { myService.findoneById(USER_ID1); } public static HystrixCircuitBreaker getCircuitBreaker() { return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); } private static HystrixCommandKey getCommandKey() { return HystrixCommandKey.Factory.asKey("findOneById"); } private void openCircuitBreakerAfteroneFailingRequest() { ConfigurationManager.getConfigInstance(). setProperty("hystrix.command.findOneById.circuitBreaker.requestVolumeThreshold", 1); }}让我绊了一会儿的另一件事是,我输入的默认注释没有特定的命令键,但是创建命令键时,它们是根据我上面指定的方法名称创建的。对于完整的示例,我还添加了注释以显示我未指定commandKey。
@HystrixCommandpublic Optional<document> findoneById(final String id) { return this.myRepo.findoneById(id);}希望这对某人有帮助。



