我正在使用 Fitnesse 测试来测试 Spring Controller 方法。 在测试的类中,applicationContext是Autowired的(通过注释)。 当从 Fixture 而不是 Spring 框架调用该方法时, Autowiring 似乎不起作用。 还有其他方法来检索 applicationContext 吗?我无法使用 XML 文件,因为我们正在使用注释。我在Google上搜索了“annotation Spring applicationContext Fitnesse Java”,但没有找到任何内容。 这是我的代码:
@Controller
public class MySpringController {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping(value = "/saveAllSecurityMaintenanceAllocations/",
method = {RequestMethod.POST })
public ResponseEntity myMethod(@RequestBody final List<String> inList,
final HttpServletRequest request) throws Exception {
if (applicationContext == null) {
System.out.println("applicationContext is null");
}
//functionality I need to test is in here and is using applicationContext
}
}
public class MyTestFixtureTest extends TableFixture {
List<String> aList = new ArrayList<String>();
public void setUp(){
aList.add("foo");
aList.add("foo2");
}
public void showResults(int fitnessRows){
MySpringController mySpringController = new MySpringController()
MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
applicationContext = UnitTestConfig.createApplicationContext();
mySpringController.myMethod(aList, httpServletRequest)
}
}
正在打印“applicationContext is null”。有谁知道如何模拟 Autowiring 或知道在 Fitnesse 测试中获取 applicationContext 的另一种方法?
最佳答案
您需要使用 AnnotationConfigApplicationContext ( http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/AnnotationConfigApplicationContext.html ) 创建 applicationContext 的(静态)实例,并将其构造函数传递给定义 Controller 应有权访问的上下文的带注释的类。 这些类(当然)可以是您的应用程序使用的真实配置,也可以是特定测试的自定义配置。
如果您有多个使用相同上下文的测试(即页面),那么在某处初始化 applicationContext 一次(存储在单例/静态实例中)并让您的装置从那里检索它是有意义的,因为创建上下文是一项昂贵的操作。创建上下文的逻辑位置是在这些测试的 SuiteSetUp 中。
关于java - 在 Fitnesse 测试中检索 applicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156305/