我正尝试测试自定义GlobalFilter
,但无法弄清缺少的内容,因为我的post
方法没有得到测试。
public class LoggingFilter implements GlobalFilter
{
static final String APP_NAME = "appName";
static final String APP_USER = "appUser";
private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);
private static void post()
{
log.debug("Not needed for the responsibility of this filter.");
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
{
pre(exchange.getRequest());
return chain.filter(exchange).then(Mono.fromRunnable(LoggingFilter::post));
}
private void pre(ServerHttpRequest request)
{
String url = request.getURI().toString();
String appName = request.getHeaders().getFirst(APP_NAME);
String appUser = request.getHeaders().getFirst(APP_USER);
log.debug("Request logged [{} ({}/{})]", url, appName, appUser);
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
// TODO: 2019-05-10 save the request url, appName, AppUser, and time of request
return null;
});
}
}
public class LoggingFilterTest extends AbstractFilterTest
{
private LoggingFilter loggingFilter;
private ServerHttpRequest serverHttpRequest;
private HttpHeaders httpHeaders;
@Override
@Before
public void setup()
{
super.setup();
loggingFilter = new LoggingFilter();
serverHttpRequest = Mockito.mock(ServerHttpRequest.class);
Mockito.when(mockServerWebExchange.getRequest()).thenReturn(serverHttpRequest);
try
{
Mockito.when(serverHttpRequest.getURI()).thenReturn(new URI("http://www.kroger.com"));
}
catch (URISyntaxException e)
{
Assert.fail();
}
httpHeaders = Mockito.spy(new HttpHeaders());
httpHeaders.add(LoggingFilter.APP_NAME, "appName");
httpHeaders.add(LoggingFilter.APP_USER, "appUser");
Mockito.when(serverHttpRequest.getHeaders()).thenReturn(httpHeaders);
}
@Test
public void noExceptionThrown()
{
loggingFilter.filter(mockServerWebExchange, mockGatewayFilterChain);
Mockito.verify(serverHttpRequest, Mockito.times(1)).getURI();
Mockito.verify(httpHeaders, Mockito.times(1)).getFirst(Mockito.eq(LoggingFilter.APP_NAME));
Mockito.verify(httpHeaders, Mockito.times(1)).getFirst(Mockito.eq(LoggingFilter.APP_USER));
}
}
public class AbstractFilterTest
{
protected GatewayFilterChain mockGatewayFilterChain;
protected ServerWebExchange mockServerWebExchange;
@Before
public void setup()
{
mockGatewayFilterChain = Mockito.mock(GatewayFilterChain.class);
Mockito.when(mockGatewayFilterChain.filter(Mockito.any(ServerWebExchange.class)))
.thenReturn(Mockito.mock(Mono.class));
mockServerWebExchange = Mockito.mock(ServerWebExchange.class);
}
}