【发布时间】:2018-07-26 16:08:36
【问题描述】:
在测试我的 Feign API 的 Hystrix 回退行为时,我收到一个错误,但我希望它会成功。
Feign接口:
这是外部服务的 api。
@FeignClient(name = "book", fallback = BookAPI.BookAPIFallback.class)
public interface BookAPI {
@RequestMapping("/")
Map<String, String> getBook();
@Component
class BookAPIFallback implements BookAPI {
@Override
@RequestMapping("/")
public Map<String, String> getBook() {
Map<String, String> fallbackmap = new HashMap<>();
fallbackmap.put("book", "fallback book");
return fallbackmap;
}
}
}
测试类
这个测试只是为了验证回退行为:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = NONE)
public class BookServiceClientTest {
@MockBean
RestTemplate restTemplate;// <---- @LoadBalanced bean
@Autowired
private BookServiceClient bookServiceClient;
@Before
public void setup() {
when(restTemplate.getForObject(anyString(), any()))
.thenThrow(new RuntimeException("created a mock failure"));
}
@Test
public void fallbackTest() {
assertThat(bookServiceClient.getBook())
.isEqualTo(new BookAPI.BookAPIFallback().getBook().get("book")); // <--- I thought this should work
}
}
配置文件
application.yml
这些文件显示了可能相关的配置:
feign:
hystrix:
enabled: true
test/application.yml
eureka:
client:
enabled: false
问题
运行应用程序时一切正常。
但是在运行此测试时,我收到以下错误。
当然,这是一个测试,所以我还是试图绕过查找。
java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: book
at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:71)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97)
我错过了什么?
附录
应用类
@SpringBootApplication
@EnableCircuitBreaker
@EnableDiscoveryClient
@EnableFeignClients
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
}
图书馆控制器
@Controller
public class LibraryController {
private final BookServiceClient bookService;
public LibraryController(BookServiceClient bookServiceClient) {
this.bookService = bookServiceClient;
}
@GetMapping("/")
String getLibrary(Model model) {
model.addAttribute("msg", "Welcome to the Library");
model.addAttribute("book", bookService.getBook());
return "library";
}
}
没有其他类。
【问题讨论】:
-
你能添加你的主应用程序类吗?
-
@DarrenForsythe 添加了
-
我无法使用您的代码重新创建骨架项目的问题。如果可能的话,可以看到所有的源代码。这可能是加载其他 bean 的问题,这将在
SpringBootTest中发生。那是完整的堆栈跟踪吗?如果您想做集成测试,还有其他可用的切片测试等更合适,并且将任何组件扫描分解为Configurations并定位需要加载的 bean 可以帮助解决这些问题。 -
@DarrenForsythe 添加了唯一的其他类:LibraryController。 pom.xml 是从 1.5.9.RELEASE Spring Boot initializr 构建的,带有 web、hystrix、eureka、feign starters。
标签: spring-boot netflix-eureka hystrix spring-cloud-feign netflix-ribbon