0

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

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

当我调用 startJob 方法时,如何在我的 JUnit 中告诉 Spring 我们正在处理一个单独的请求?

我有以下代码:

@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);
    }
}
4

0 回答 0