Jeanne Lane
Jeanne Lane

Reputation: 505

Retrieving applicationContext in Fitnesse test

I am testing a Spring Controller method with a Fitnesse test. In the tested class, applicationContext is Autowired (through annotations). It looks like the autowiring isn't working when the method is called from a Fixture rather than the Spring Framework. Is there another way to retrieve applicationContext? I can't use the XML file because we are using annotations. I have searched Google for "annotation Spring applicationContext Fitnesse Java", but I didn't find anything. Here is my code:

@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" is printing. Does anyone know how to mock autowiring or know another way to get applicationContext in a Fitnesse test?

Upvotes: 0

Views: 1214

Answers (1)

Fried Hoeben
Fried Hoeben

Reputation: 3272

You'll want to create a (static) instance of your applicationContext using AnnotationConfigApplicationContext (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/AnnotationConfigApplicationContext.html) passing its constructor the annotated classes that define the context your controller should have access to. These classes can (of course) be the real configuration your application uses, or a custom configuration for a particular test.

If you'll have multiple tests (i.e. pages) that use the same context it makes sense to have the applicationContext be initialized once (stored in a singleton/static instance) somewhere and have your fixtures retrieve it from there, since creating a context is an expensive operation. A logical place to create the context would be in the SuiteSetUp for these tests.

Upvotes: 1

Related Questions