在JUnit中使用请求范围时出现Spring单例问题

时间:2015-08-13 11:29:33

标签: java spring junit request-mapping

当我运行JUnit测试时,每次尝试调用JobConfigurationREST.startJob方法时,Spring都错误地使用了JobRunner类的相同实例。

但是,当我通过REST Web服务调用调用时,Spring为我提供了一个不同的JobRunner类实例,这就是我想要的。

如何在我的JUnit中告诉Spring我在调用startJob方法时处理单独的请求?

我有以下代码:

@RestController
@RequestMapping("/jobConfiguration")
public class JobConfigurationREST extends RESTBase {

    @Autowired
    private WebApplicationContext context;

    @RequestMapping(value="/startJob", method = RequestMethod.POST, produces="application/json")
    @ResponseBody
    public ResponseEntity<String> startJob(@RequestBody String jobConfigInfo) {
            JobRunner jr = getJobRunner();
    }

    private JobRunner getJobRunner() {
        return (JobRunner)context.getBean("jobRunner");
    }
}

@Component
@Scope("request")
public class JobRunner{
}

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(loader = GenericXmlWebContextLoader.class, locations = {"classpath:/config/spring-config-test.xml"})
public class JobConfigurationRESTTest {

    @Autowired
    private JobConfigurationREST jcREST;

    @Test
    public void testSingletonBug() throws IOException{
        String jobConfig;
        ResponseEntity<String> responseJobStatus = jcREST.startJob(jobConfig);
        ResponseEntity<String> responseJobStatus2 = jcREST.startJob(jobConfig);
    }
}

0 个答案:

没有答案