繁体   English   中英

单元测试中的Spring Cloud Gateway注入不起作用

[英]Spring Cloud Gateway injection in Unit Tests is not Working

我有一个带有注入属性的全局过滤器。

public class AuthenticationGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private Permission permission;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        long serviceId = 0;

        try {
            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders headers = request.getHeaders();

            String fromKey = headers.getFirst("x-api-key");
            String fromIp = headers.getFirst("x-forwarded-for");
            String fromSubject = headers.getFirst("******");

            URI rqUrl = request.getURI();
            String path = rqUrl.getPath();
            serviceId = Long.parseLong(path.split("/")[6]);
            permission.check(permission.identity(fromKey, fromSubject, fromIp), serviceId);

            return chain.filter(exchange);
        } catch (PermissionException e) {
            exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        } catch (IllegalArgumentException e) {
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return Mono.empty();
    }
}

当我运行应用程序时,注入效果完美

@EnableDiscoveryClient
@SpringBootApplication
@EnableConfigurationProperties(ApiGatewayProperties.class)
@Import({ PermitAllSecurityConfiguration.class, CustomAttributesConfiguration.class })
@ImportResource(value = { "classpath:datasource.xml", "classpath:api-gateway-unico-beans.xml" })
public class ApiGatewayUnicoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayUnicoApplication.class, args);
    }
}

使用此配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd  
                        http://www.springframework.org/schema/cache 
                        http://www.springframework.org/schema/cache/spring-cache.xsd                                      
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd">


<cache:annotation-driven
    cache-manager="cacheManager" />

<context:annotation-config />
<context:component-scan
    base-package="*****.apigatewayunico" />

<bean
    class="*****.apigatewayunico.filters.AuthenticationGlobalFilter" />

<bean class="*****.apigatewayunico.Persistence"
    p:sql="SELECT rep.url FROM RestService rs, RestEndpoint rep WHERE rep.id = rs.endpoint_id AND rs.id = ? AND rs.available = true" />

<bean id="permission"
    class=*****.permission.Permission" />

问题是,当我进行单元测试时,该属性通过不在测试的过滤器中注入到单元测试中,这给我关于无法定位可以满足此依赖关系的bean的错误。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@DirtiesContext
public class AuthenticationGlobalFilterIntegrationTests extends BaseWebClientTests {
    @Autowired
    private Permission permission;

    @Before
    public void setup() {
        super.setup();

        reset(permission);
        permission.check(null, 123456L);
    }

    @Test
    public void runSucessTest() {
        expectLastCall();
        replay(permission);

        testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.OK);
    }

    @Test
    public void runPermissionExceptionTest() throws Exception {
        expectLastCall().andThrow(new PermissionException(""));
        replay(permission);

        testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
    }

    @EnableAutoConfiguration
    @SpringBootConfiguration
    @Import(DefaultTestConfig.class)
    @ImportResource(value = "classpath:authentication-filter-test-beans.xml")
    public static class TestConfig {
    }
}

authentication-filter-test-beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:api-gateway-unico-test-beans.xml" />

    <bean id="authenticationFilter"
        class="*****.apigatewayunico.filters.AuthenticationGlobalFilter">
    </bean>
</beans>

api-gateway-unico-test-beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd"
    default-lazy-init="false">

    <bean id="mockSupport" class="org.easymock.EasyMockSupport" />

    <bean id="pp" factory-bean="mockSupport"
        factory-method="createNiceMock"
        c:_0="*****.permission.PermissionPersistence" />
    <bean id="permission" factory-bean="mockSupport"
        factory-method="createNiceMock"
        c:_0="*****.permission.Permission" />
    <bean id="jdbc" factory-bean="mockSupport"
        factory-method="createNiceMock"
        c:_0="org.springframework.jdbc.core.JdbcTemplate" />
    <bean id="descoveryClienteMock" factory-bean="mockSupport"
        factory-method="createNiceMock"
        c:_0="org.springframework.cloud.client.discovery.DiscoveryClient" />
    <bean id="serviceInstanceMock" factory-bean="mockSupport"
        factory-method="createNiceMock"
        c:_0="org.springframework.cloud.client.ServiceInstance" />
</beans>

现在,当我尝试将单元测试的配置xml添加到单元测试中的@ConextConfiguration批注中时,我得到了一个与Reactor依赖项相关的测试!

org.springframework.context.ApplicationContextException:无法启动反应式Web服务器

通过使用@Lazy注释依赖项来解决

暂无
暂无

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

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