2

少し問題があります。典型的な質問だと思います。しかし、私は良い例を見つけることができません。私のアプリケーションはジャージーを使用しています。そして、テストとしてクライアントでコントローラーをテストしたいと思います。コントローラーにはプライベート フィールドがあります - StudentService。テストをデバッグすると、そのフィールドは null です。これはエラーにつながります。そして、このフィールドを注入する必要があります。私はこれを試しました:私のコントローラー

@Path("/student")
@Component
public class StudentResourse {
    @Autowired
    private StrudentService service; // this field Spring does not set

    @Path("/getStudent/{id}")
    @GET
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    public Student getStudent(@PathParam("id") long id) {
         return service.get(id);
    }  
}

私のJUnitテストクラス:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config.xml")
@TestExecutionListeners({ DbUnitTestExecutionListener.class,
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class })
public class StudentResourseTest extends JerseyTest {
private static final String PACKAGE_NAME = "com.example.servlet";
private static final String FILE_DATASET = "/data.xml";
@Autowired
private StudentService service; // this field is setted by Spring, but I do not need this field for test

public StudentResourseTest() {
    super(new WebAppDescriptor.Builder(PACKAGE_NAME).build());
}

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

@Override
protected AppDescriptor configure() {
    return new WebAppDescriptor.Builder("restful.server.resource")
            .contextParam("contextConfigLocation",
                    "classpath:/config.xml").contextPath("/")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .requestListenerClass(RequestContextListener.class).build();
}

@Test
@DatabaseSetup(FILE_DATASET)
public void test() throws UnsupportedEncodingException {
        ClientResponse response = resource().path("student").path("getStudent")
                .path("100500").accept(MediaType.APPLICATION_XML)
                .get(ClientResponse.class);
        Student student = (Student) response.getEntity(Student.class);
}  }

その問題はテストクラスにあると思います。テスト中ではないアプリケーションを実行すると、生徒に直接リクエストでき、すべてが正常に機能するからです。しかし、クラスをテストすると、コントローラーの内部フィールドが設定されません。このバグを修正するには?回答ありがとうございます。

これは私のconfig.xmlにあります

<context:component-scan base-package="com.example" />
<bean id="StudentResourse" class="com.example.servlet.StudentResourse">
    <property name="service" ref="studentService" />
</bean>
<bean id="service" class="com.example.service.StudentServiceImpl" />
4

2 に答える 2

1

configure()1 つの問題は、コンストラクターとメソッドでテスト アプリケーションを構成しようとしている可能性があります。この場合、メソッドが呼び出されないため、このメソッドで定義されているすべてのものをconfigure()使用していない可能性があるため、両方ではなくどちらか一方を使用してください。SpringServlet

于 2013-10-15T16:09:18.717 に答える