简体   繁体   English

Zuul 中过滤器的 SpringBoot Junit 测试

[英]SpringBoot Junit testing for filters in Zuul

I'm new to Zuul J-unit testing.我是 Zuul J 单元测试的新手。 I have a couple of filters which is ChangeRequestEntityFilter and SessionFilter, Where I pasted my filtercode below.我有几个过滤器,分别是 ChangeRequestEntityFilter 和 SessionFilter,我在下面粘贴了我的过滤器代码。 Can someone tell me how to write a Junit for the filter.有人能告诉我如何为过滤器编写一个 Junit。 I've searched and trying to use MockWire for the unit testing(Also I pasted my empty methods with basic annotations and WireMock port).我已经搜索并尝试使用 MockWire 进行单元测试(我还粘贴了带有基本注释和 WireMock 端口的空方法)。 I need at-least one proper example how this J-unit for Zuul works.我至少需要一个合适的例子来说明这个用于 Zuul 的 J-unit 是如何工作的。 I've referred the http://wiremock.org/docs/getting-started/ doc.我已经提到了http://wiremock.org/docs/getting-started/ doc。 Where I got what to do, but not how to do.我在哪里可以做什么,但不知道怎么做。

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;
    }

}

I know ,I'm asking more.我知道,我要问更多。 But give me any simple working complete example, I'm fine with it.但是给我任何简单的工作完整示例,我很好。

My current code with basic annotations and WireMock port.我当前的代码带有基本注释和 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() {

    }
}

Have you tried @MockBean?你有没有试过@MockBean?

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

"When @MockBean is used on a field, as well as being registered in the application context, the mock will also be injected into the field. Typical usage might be:" “当@MockBean 在一个字段上使用时,以及在应用程序上下文中注册时,模拟也将被注入到该字段中。典型用法可能是:”

@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 {
     }

}

Here there is another approach:这里有另一种方法:

    private ZuulPostFilter zuulPostFilter;

    @Mock
    private anotherService anotherService;

    @Mock
    private HttpServletRequest request;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        MonitoringHelper.initMocks();
        zuulPostFilter = new ZuulPostFilter(anotherService);
        doNothing().when(anotherService).saveInformation(null, false);
    }

    @Test
    public void postFilterTest() {
        log.info("postFilterTest");
        RequestContext context = new RequestContext();
        context.setResponseDataStream(new ByteArrayInputStream("Test Stream".getBytes()));
        context.setResponseGZipped(false);
        RequestContext.testSetCurrentContext(context);
        when(request.getScheme()).thenReturn("HTTP");
        RequestContext.getCurrentContext().setRequest(request);

        ZuulFilterResult result = zuulPostFilter.runFilter();

        assertEquals(ExecutionStatus.SUCCESS, result.getStatus());
        assertEquals("post", zuulPostFilter.filterType());
        assertEquals(10, zuulPostFilter.filterOrder());
    }

In this case you can test the filter and mock the services inside it without having to autowire it, the problem with the @autowired is that if you have services inside the filter, then it is going to be an integration test that is going to be more difficult to implement.在这种情况下,您可以测试过滤器并模拟其中的服务,而无需自动装配它,@autowired 的问题在于,如果您在过滤器中有服务,那么它将是一个集成测试更难实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM