gpt4 book ai didi

microservices - Zuul 过滤器的 SpringBoot Junit 测试

转载 作者:行者123 更新时间:2023-12-05 06:32:03 24 4
gpt4 key购买 nike

我是 Zuul J-unit 测试的新手。我有几个过滤器,它们是 ChangeRequestEntityFilter 和 SessionFilter,我在下面粘贴了我的过滤器代码。谁能告诉我如何为过滤器编写 Junit。我已经搜索并尝试使用 MockWire 进行单元测试(我还粘贴了带有基本注释和 WireMock 端口的空方法)。我至少需要一个适当的例子,说明 Zuul 的 J-unit 是如何工作的。我提到了 http://wiremock.org/docs/getting-started/医生。我知道该做什么,但不知道该怎么做。

public class ChangeRequestEntityFilter extends ZuulFilter {

@Autowired
private UtilityHelperBean utilityHelperBean;

@Override
public boolean shouldFilter() {
// //avoid http GET request since it does'nt have any request body
return utilityHelperBean.isValidContentBody();
}

@Override
public int filterOrder() {
//given priority
}

@Override
public String filterType() {
// Pre
}

@Override
public Object run() {

RequestContext context = getCurrentContext();

try {
/** get values profile details from session */
Map<String, Object> profileMap = utilityHelperBean.getValuesFromSession(context,
CommonConstant.PROFILE.value());

if (profileMap != null) {
/** get new attributes need to add to the actual origin microservice request payload */
Map<String, Object> profileAttributeMap = utilityHelperBean.getProfileForRequest(context, profileMap);
/** add the new attributes in to the current request payload */
context.setRequest(new CustomHttpServletRequestWrapper(context.getRequest(), profileAttributeMap));
}

} catch (Exception ex) {
ReflectionUtils.rethrowRuntimeException(new IllegalStateException("ChangeRequestEntityFilter : ", ex));
}

return null;
}

}

我知道,我要求更多。但是给我任何简单的工作完整示例,我都可以接受。

我当前的代码带有基本注释和 WireMock 端口。

@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
@EnableZuulProxy
public class ChangeRequestEntityFilterTest {

@Rule
public WireMockRule wireMockRule = new WireMockRule(8080);

@Mock
ChangeRequestEntityFilter requestEntityFilter;

int port = wireMockRule.port();

@Test
public void changeRequestTest() {

}
}

最佳答案

你试过@MockBean了吗?

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html

“当@MockBean 在字段上使用时,以及在应用程序上下文中注册时,模拟也会被注入(inject)到字段中。典型用法可能是:”

@RunWith(SpringRunner.class)
public class ExampleTests {

@MockBean
private ExampleService service;

@Autowired
private UserOfService userOfService;

@Test
public void testUserOfService() {
given(this.service.greet()).willReturn("Hello");
String actual = this.userOfService.makeUse();
assertEquals("Was: Hello", actual);
}

@Configuration
@Import(UserOfService.class) // A @Component injected with ExampleService
static class Config {
}

}

关于microservices - Zuul 过滤器的 SpringBoot Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51512075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com