SpringBoot Junit测试Zuul中的过滤器

时间:2018-07-25 06:20:37

标签: microservices zuul-testing

我是Zuul J单元测试的新手。我有几个过滤器,分别是ChangeRequestEntityFilter和SessionFilter,我在下面粘贴了我的过滤器代码。有人可以告诉我如何为过滤器编写Junit。我搜索并尝试使用MockWire进行单元测试(此外,我还用基本注释和WireMock端口粘贴了空方法)。我至少需要一个适当的例子,这个用于Zuul的J单元如何工作。我已经推荐了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() {

    }
}

2 个答案:

答案 0 :(得分:1)

您尝试过@MockBean吗?

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

“当在字段上使用@MockBean以及在应用程序上下文中注册@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 {
     }

}

答案 1 :(得分:0)

这里有另一种方法:

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

在这种情况下,您可以测试过滤器并模拟其中的服务而无需自动装配,@autowired的问题在于,如果您在过滤器中有服务,则它将成为一个集成测试,即实施起来会更加困难。