JerseyTest for Spring-Jersey应用程序中的资源模型验证失败

时间:2016-03-21 11:24:51

标签: spring jersey jersey-2.0 jersey-test-framework

我有一个带注释的Spring-Jersey应用程序。我正在尝试使用JerseyTest为我的控制器设置单元测试。我在运行测试时遇到以下错误,我无法弄清楚。我错过了什么?

SEVERE: Following issues have been detected: 
WARNING: No injection source found for a parameter of type public com.example.services.dto.UnitDto com.example.apis.UnitResource.getUnits(com.example.services.dto.PointDto) throws com.example.exceptions.PointOutsideBounds at index 2.

Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public com.example.services.dto.UnitDto com.example.apis.UnitResource.getUnits(com.example.services.dto.PointDto) throws com.example.exceptions.PointOutsideBounds at index 2.; source='ResourceMethod{httpMethod=GET, consumedTypes=[], producedTypes=[application/json], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.example.apis.UnitResource, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@31a5870e]}, definitionMethod=public com.example.services.dto.UnitDto com.example.apis.UnitResource.getUnits(com.example.services.dto.PointDto) throws com.example.exceptions.PointOutsideBounds, parameters=[Parameter [type=class com.example.services.dto.PointDto, source=contains, defaultValue=null]], responseType=class com.example.services.dto.UnitDto}, nameBindings=[]}']
    at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:555)

控制器类如下:

@Component
@Path("/app/units")
public class UnitResource {
    @Context
    private UriInfo uriInfo;
    @Context
    private Request request;

    @Inject
    private UnitService unitService;

    @Inject
    public UnitResource(@Named("UnitService") UnitService unitService) {
        this.unitService = unitService;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Timed(absolute = true, name = "getUnitForPoint")
    public UnitDto getUnits(@QueryParam("contains") @NotNull PointDto point) throws PointOutsideBounds {
        return unitService.getUnitForPoint(point);
    }
}

测试类如下:

public class UnitResourceTest extends JerseyTest {

    @Mock
    private UnitService unitService;

    @Override
    protected ResourceConfig configure() {
        ResourceConfig rc = new ResourceConfig()
        //      .register(new UnitResource(Mockito.mock(UnitService.class))) -- has the same effect
                .register(UnitResource.class)
                .property("contextConfig", new AnnotationConfigApplicationContext(ApplicationConfiguration.class));

        enable(TestProperties.LOG_TRAFFIC);
        enable(TestProperties.DUMP_ENTITY);
        forceSet(TestProperties.CONTAINER_PORT, "0");

        return rc;
    }

    @Before
    public void setUp() throws Exception {
        super.setUp();
        initMocks(this);
    }

    @Override
    protected TestContainerFactory getTestContainerFactory() {
        return new InMemoryTestContainerFactory();
    }

    @Test
    public void testGetUnit() throws PointOutsideBounds {

        Response response = target()
                .path("/app/units")
                .queryParam("contains", new Point(0.0,0.0).toJson())
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();

        assertThat(response.getStatus(), is(Response.Status.OK));
    }
}

应用程序配置类是:

@Configuration
@ComponentScan("com.example")
public class ApplicationConfiguration {
    @Bean(name="UnitService")
    public UnitService unitService() {
        return new UnitService();
    }
}

测试配置的My Gradle依赖项是:

dependencies {
    // Using junit-dep package to get junit without hamcrest dependency
    testCompile("junit:junit-dep:4.8.2")
    testCompile("org.hamcrest:hamcrest-all:1.3")
    testCompile("org.mockito:mockito-all:1.8.4")
    testCompile ('org.glassfish.jersey.test-framework:jersey-test-framework-core:2.22.2')
    testCompile('org.glassfish.jersey.test-framework.providers:jersey-test-framework-provider-inmemory:2.22.2')
}

configurations {
    testCompile.exclude group: 'org.glassfish.jersey.ext', module: 'jersey-spring3'
}

我找到thisthis,但都没有解决我的问题。

1 个答案:

答案 0 :(得分:0)

注意:在大多数情况下,此答案适用于所有@XxxParam带注释的参数。

PointDto参数似乎是问题

public UnitDto getUnits(@QueryParam("contains") @NotNull PointDto point)

查询参数是字符串。 Jersey能够将该String转换为一些基本类型,如intbooleanDate等。但它不知道如何从该字符串创建PointDto 。这并不意味着我们无法使用自定义类型。我们只需遵循一些规则:

  1. 有一个接受String的构造函数。然后我们需要自己从String构造对象。例如

    public PointDto(String param) {
        Map<String, Object> map = parseJson(param);
        this.field1 = map.get("field1");
        this.field2 = map.get("field2");
    }
    

    这有点工作。

  2. 另一种选择是在课堂上使用静态fromString(String)或静态valueOf(String)。 Jersey将调用此方法来构造对象。例如,您可以拥有PointDto

    public static PointDto fromString(String param) {
        PointDto dto = parseJson(param);
        return dto;
    }
    
  3. 您可以拥有ParamConverterProvider。我不会举一个例子,但你可以在this good article中阅读更多关于如何实现它的内容。您还可以看到this post

  4. 请注意,此答案中显示的信息位于@QueryParam的javadoc中。