Spring 3 and Junit 4 NullPointerException - java

I have a problem in setting up a unit test based on Spring 3 and Junit 4
My code is fairly basic at the moment as can be seen below
#ContextConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
public class PSTemplateDAOTests {
private static final Logger logger = Logger.getLogger(
PSTemplateDAOTests.class.getName());
#Autowired
ApplicationContext ctx;
#Test
public void testone ()
{
logger.info("Run testone");
}
#Test
public void testtwo ()
{
logger.info("Run testtwo");
}
}
However when I come to run this I encounter a NPE as below :-
java.lang.NullPointerException
at org.springframework.test.context.ContextLoaderUtils.resolveContextLoaderClass(ContextLoaderUtils.java:153)
at org.springframework.test.context.ContextLoaderUtils.resolveContextLoader(ContextLoaderUtils.java:84)
at org.springframework.test.context.ContextLoaderUtils.buildMergedContextConfiguration(ContextLoaderUtils.java:298)
at org.springframework.test.context.TestContext.<init>(TestContext.java:100)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:117)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:119)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
If I comment out the #ContextConfiguration annotation the test(s) will run however then I encounter the following :-
May 20, 2015 8:28:29 AM org.springframework.test.context.TestContext <init>
INFO: #ContextConfiguration not found for class [class uk.gov.moj.ps.dao.PSTemplateDAOTests]
May 20, 2015 8:28:29 AM org.springframework.test.context.TestContextManager retrieveTestExecutionListeners
INFO: #TestExecutionListeners is not present for class [class uk.gov.moj.ps.dao.PSTemplateDAOTests]: using defaults.
2015-05-20 08:28:29 INFO PSTemplateDAOTests:34 - Run testtwo
2015-05-20 08:28:29 INFO PSTemplateDAOTests:27 - Run testone
Which makes sense as there is no ContextConfiguration element to allow Spring to set up the environment.
I have also tried different ContextConfiguration set ups with both normal files and location elements, neither setting gets past the initial NPE error.
I'm using Eclipse Kepler and jre 1.7 although I have also switched round jre's without any success.
Any assistance would be much appreciated.
Ok - I realise I wasn't clear enough in my description, it is my first question on SO, anyway some further clarification.
I am aware that the contextconfiguration is generally configured with a path to a file via location or just a simple path, I have tried both of these and also the default value with no path.
The whole crux of the matter is that the #Contextconfiguration triggers a NPE regardless of what is supplied to it, in fact spring doesn't even seem to initialise correctly.
I hope this makes things clearer

Most examples from the Spring Framework Reference Manual explicitely defines the location of the XML file, or #Configuration classes used to populate the application context.
You can use a plain #ContextConfiguration annotation without any configuration, but the default may not be what you expect :
If you omit both the locations and value attributes from the #ContextConfiguration annotation, the TestContext framework will attempt to detect a default XML resource location. Specifically, GenericXmlContextLoader detects a default location based on the name of the test class. If your class is named com.example.MyTest, GenericXmlContextLoader loads your application context from "classpath:/com/example/MyTest-context.xml".
IMHO, you should explicitely pass the configuration of the application context to #ContextConfiguration. Examples from same doc :
// use test.config.xml from classpath
#ContextConfiguration("/test-config.xml")
public class XmlApplicationContextTests {
// class body...
}
// use TestConfig as a #Configuration class
#ContextConfiguration(classes = TestConfig.class)
public class ConfigClassApplicationContextTests {
// class body...
}

I don't think you can autowire ApplicationContext like you are trying, and I'm not sure why you would want to, especially in a test.
But if you really want to, try the code below:
import java.util.logging.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
#ContextConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
public class PSTemplateDAOTests implements ApplicationContextAware {
private static final Logger logger = Logger.getLogger(PSTemplateDAOTests.class.getName());
private ApplicationContext ctx;
#Test
public void assertContextPreset() {
Assert.notNull(ctx);
}
#Test
public void testone() {
logger.info("Run testone");
}
#Test
public void testtwo() {
logger.info("Run testtwo");
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
ctx = applicationContext;
}
}
Like others have said, you also seem to be missing some application context configuration. You should either provide a location as a parameter to ContextConfiguration or create a context file named PSTemplateDAOTests-context.xml in the same package as the test.

Related

Spring Injecting Beans from src folder in test folders

I have utility classes exposed as beans in my source folders. I want to use some of those utilities in my test classes written in junit 4. For example , I have a utility class that has methods which marshal an object into JSON string. I want to inject this utility bean in my test class. I am unable to inject these beans using Autowired annotation. Should I copy all these classes over to test folder?
Edit:
I am trying to inject jsonUtil. Below is how my code looks like.
import static org.junit.Assert.*;
import java.math.BigDecimal;
#RunWith(MockitoJUnitRunner.class)
#SpringApplicationConfiguration(classes = ProxyApplicationMock.class)
public class ProxyApplicationMock {
#Mock
public SoapClient soapClientMock;
private JsonUtil jsonUtil;
Main Class
public class ProxyApplication {
public static void main(String[] args) {
SpringApplication.run(ProxyApplication.class, args);
}
}
Your main classes can be seen by your test classes, but not the other way around. So no, you don't need to copy them.
If your utility class is declared as a Spring managed bean in your test Spring context configuration (the class -or XML file- declared in the #ContextConfiguration) which may and probably should be different from your main configuration.
Then you can inject it in any Spring managed class, which includes your test classes if it's using the SpringJUnit4ClassRunner.
EDIT:
To sum up what we discussed in the comments, the main problem is that your test runner is not a SpringRunner (alias for SpringJUnit4ClassRunner), and thus JUnit is not running your test in a Spring context. Have a look at a test example here.
The simplest test case will look like this.
#RunWith(SpringRunner.class)
#SpringBootTest
public class CityRepositoryIntegrationTests {
#Autowired
private MySpringBean springBean;
//...
}
But as often with Spring Boot, there's some magic happening behind. #SpringBootTest is a convenient annotation that will detect automatically a class annotated with #SpringBootConfiguration, meaning if you don't have a specific Spring configuration for your test, it will use your main Spring configuration, and thus include and instanciate all the beans for your main app, and that's not usually what we want in a unit test cause we want to test a class independently by mocking its dependencies.
What you can do, is provide the Spring compenent classes you want to include in your tests, as such:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MySpringBean.class)
public class CityRepositoryIntegrationTests {
#Autowired
private MySpringBean springBean;
#Mock
private MyMockedSpringBeanDependency mocked;
//...
}
This question is to Matt, since adding comment is throwing error saying only one additional use can be notified.
NOTE: Not an Answer
I have an Application class & many config classes which are imported in Application class. Earlier it was #Configuration, which I converted to #SpringBootConfiguration in Application class and the actual Config class, whos bean I am trying to mock. Ended up in
java.lang.NoSuchMethodError: org.springframework.boot.SpringApplication.<init>([Ljava/lang/Object;)V
at org.springframework.boot.test.context.SpringBootContextLoader.getSpringApplication(SpringBootContextLoader.java:121)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:84)
Please suggest How do I mock, I have the same setup as specified in the ticket.
#Bean
public CacheManager cacheManager()
{
EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
factoryBean.setShared(true);
return new EhCacheCacheManager(factoryBean.getObject());
}
}

Best way to exclude unit test #Configurations in Spring?

In my Spring Boot project, I have a main class annotated with #SpringBootConfiguration. I also have some unit tests that use #SpringApplicationConfiguration that points to an inner class that defines a Spring context for usage in my unit test (using some mocks).
I now want to write an integration test that starts the full context of my application. However, this does not work as it also picks up the Spring contexts that are defined as inner classes in other unit tests.
What would be the best way to avoid that? I did see the exclude and excludeName properties on #SpringBootConfiguration, but I am unsure how to use them.
UPDATE:
Some code to explain the problem more:
My main class:
package com.company.myapp;
#SpringBootApplication
#EnableJpaRepositories
#EnableTransactionManagement
#EntityScan(basePackageClasses = {MyApplication.class, Jsr310JpaConverters.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
I have a unit test for Spring REST Docs:
package com.company.myapp.controller
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration
#WebAppConfiguration
public class SomeControllerDocumentation {
#Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
// Some test methods here
// Inner class that defines the context for the unit test
public static class TestConfiguration {
#Bean
public SomeController someController() { return new SomeController(); }
#Bean
public SomeService someService() { return new SomeServiceImpl(); }
#Bean
public SomeRepository someRepository() { return mock(SomeRepository.class);
}
So the unit test uses the context defined in the inner class. Now I want a different test that tests if the "normal" application context of the app starts up:
package com.company.myapp;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(MyApplication.class)
#WebAppConfiguration
public class MyApplicationTest {
#Autowired
private ApplicationContext applicationContext;
#Test
public void whenApplicationStarts_thenContextIsInitialized() {
assertThat(applicationContext).isNotNull();
}
}
This test will now not only wire the stuff it should, but also the beans from the SomeControllerDocumentation.TestConfiguration inner class. This I want to avoid.
You could use profiles: annotate the relevant configuration beans with #Profile("unit-test") and #Profile("integration-test") and inside the tests specify which profile should be active via #ActiveProfiles.
However, it sounds like you could avoid the problem altogether just by reorganising your configuration structure. It's hard to assume anything without seeing any code, though.
Since Spring Boot 1.4, the problem can be avoided by annotation the configuration in the unit tests with #TestConfiguration
I think you talk about #Ignore

FindBugs null issue with Spring #Autowired in Eclipse

I am using the findbugs Eclipse plugin (3.0.1.20150306-5afe4d1), spring (4.2.2.RELEASE), and eclipse (Mars.1 (4.5.1)) together and I am receiving the following FindBugs bug in Eclipse.
Non-null field env is not initialized by new
org.test.app.config.AppConfiguration() [Scary(8), Normal confidence]
I am using using the default constructor and using autowiring to initialize the env variable. I also have a PostConstruct annotation which gets called after everything is wired and accesses the env variable to make sure it was initialized correctly.
How can I make this error disappear without turning off the FindBugs plugin and still using the #Autowired annotation?
package org.test.app.config;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
#Configuration
#ComponentScan(basePackages = { "org.test.app" })
#PropertySource("classpath:/${spring.profiles.active:local}.properties")
public class AppConfiguration {
private static final Logger log = LoggerFactory.getLogger(AppConfiguration.class);
#Autowired
private Environment env;
/**
* Dump profile info.
*/
#PostConstruct
public void details() {
log.debug("** App application context, active profile(s)={}", Arrays.toString(env.getActiveProfiles()));
}
}
Update
I tried using a constructor per #spoonybard896 suggestion, but it did not work. I received the following error.
java.lang.NoSuchMethodException: org.test.app.config. AppConfiguration $$EnhancerBySpringCGLIB$$cbece1d7.<init>()
[STDOUT] at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_60]
[STDOUT] at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_60]
[STDOUT] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiat‌​e(SimpleInstantiationStrategy.java:80) ~[na:na]
How about using a non-default constructor instead?
private final Environment env;
#Autowired
public AppConfiguration(final Environment env) {
this.env = env;
}
EDIT
The above approach would work for a #Controller instance, but will not work for #Configuration. After doing some quick research it turns out that:
#Configuration is meta-annotated with #Component, therefore #Configuration classes are candidates for component scanning (typically using Spring XML's <context:component-scan/> element) and therefore may also take advantage of #Autowired/#Inject at the field and method level (but not at the constructor level).
I'm thinking that unless there is some kind of addon for FindBugs that understands Spring annotations (I do not know of one) then you may just need to apply a filter to the FindBugs plugin and have it ignore that particular error in that particular file(or in any Configuration class in general). In Eclipse check out Preferences -> Java -> Findbugs -> Filter Files, and check out this link which describes a similar problem and resolution, but just make sure to filter out only the error you want. The goal would not be turn FindBugs off, but instead have it just ignore this one case.
EDIT 2
Adding an annotation to the class will suppress the FindBugs error for this file only.
#SuppressFBWarnings(
value="NP_NONNULL_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR",
justification="Overriding the check on the env variable because Spring will automatically initialize the variable after the constructor is called and before any public methods are called.")

Using Spring's ResourceLoader in tests

I'm #Autowireing a org.springframework.core.io.ResourceLoader into one of my #Service classes.
During the tests, I'd like to get access to an instance of a ResourceLoader, so that it can be injected into the service being tested. What's the best way to get a fully functional instance of ResourceLoader during your tests?
If that's not possible, is there an alternative to ResourceLoader? Essentially, I need to have my service read some static files from the project.
Update:
Started using #RunWith(SpringJUnit4ClassRunner.class) + #ContextConfiguration on my test; however, the ResourceLoader that is now being injected via #Autowire into my service behaves differently than usual (ie. when it's not in the test context). In the test, ResourceLoader#getResource returns a Resource pointing to bad relative path, rather than the proper absolute path which appears during a regular execution.
Some more information discovered while debugging:
During tests, the #Autowired resourceLoader is an instanceof org.springframework.context.support.GenericApplicationContext
During regular execution, resourceLoader is an instance of org.springframework.web.context.support.XmlWebApplicationContext
You can use a DefaultResourceLoader. It handles URL and classpath resources which should be enough for simple tests.
DefaultResourceLoader doesn't need any special setup. Just create a new instance and pass it into your test.
What kind of test do you want to write?
If it's a unit test, you should probably mock ResourceLoader and inject that mock into the service instance. (Use mockito for example)
If it's an integration test, you would be better off using the Spring TestContext framework. Create a spring context that contains all components needed for the test, then annotate your test class with #RunWith(SpringJUnit4ClassRunner.class) +
#ContextConfiguration, which will make it possible to autowire fully configured beans (e.g. the service instance to be tested) in the test class.
I suppose you have your service defined as something like this:
public class ResourceService {
#Autowired
ResourceLoader loader;
}
Now, when you write your test for ResourceService :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "classpath:test-config.xml" })
public class ResourceServiceTest {
#Autowired
ResourceService resourceService;
#Test
public void test() {
...
}
}
The Spring TestContext Framework configures instances of your test classes via Dependency Injection. So, when you autowire ResourceService in your test class, Spring will inject the autowired ResourceLoader property into ResourceService.
ENVIRONMENT:
Java: 17
Springboot: 2.6.2
Junit-jupiter:5.8.2
Generally integration tests will need to start up a container to execute the test cases. This can be achieved using the following code:
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertTrue;
#RunWith(SpringRunner.class)
#SpringBootTest
#TestPropertySource(locations = "classpath:application-integration-test.properties")
class TemplateKeyValidatorIT {
#Autowired
ResourceLoader resourceLoader;
#Autowired
private ResourceLoaderService resourceLoaderService;
#Test
void testResourceLoading() {
// Given
String fileName = "myTestFile.txt";
// When
File file = resourceLoaderService.load(fileName);
// Then
assertTrue(file.exists());
}
}
#RunWith(SpringRunner.class): SpringRunner is the base Spring framework Runner. It extends SpringJUnit4ClassRunner, but it’s just an alias to that class.
#SpringBootTest: Annotation is needed to bootstrap the entire container; it creates an ApplicationContext that will be used by the integration tests.
#TestPropertySource(locations = "classpath:application-integration-test.properties"): Loads integration specific application properties.
Note: this will boot strap the real application context but you can separate test configuration class using:
#TestConfiguration
public class MyTestContextConfiguration {
#Bean
public ResourceLoaderService resourceLoaderService() {
return new ResourceLoaderService() {
// implement methods
};
}
}
And this can then be impoerted by your test class using:
#Import(MyTestContextConfiguration.class)

Why unit testing with Spring 3.1 WebMvcConfig fails?

From Spring 3.1, we can use JavaConfig more easily thanks to #Enable* annotations.
So I made a WebConfig to set WebMvc configuration, and tried to test it. But if I extends WebMvcConfigurerAdapter or WebMvcConfigurationSupport with WebConfig the unit test fails because of lack of ServletContext. The code and messages look like below.
WebConfig.java
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {}
Test.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=WebConfig.class)
public class TestFail {
#Test
public void test() {}
}
Message
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
...
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:253)
at com.zum.news.comments.web.WebConfig$$EnhancerByCGLIB$$8bbfcca1.CGLIB$defaultServletHandlerMapping$10(<generated>)
at com.zum.news.comments.web.WebConfig$$EnhancerByCGLIB$$8bbfcca1$$FastClassByCGLIB$$19b86ad0.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:215)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:280)
at com.zum.news.comments.web.WebConfig$$EnhancerByCGLIB$$8bbfcca1.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:149)
... 41 more
How to unit test the WebConfig properly?
Edit
As Garcia said, this bug is fixed in Spring 3.2.0.RC1.
Just add #WebAppConfiguration annotation in the test class.
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(classes=WebConfig.class)
public class TestFail {
#Test
public void test() {}
}
As Guido mentioned previously, this has been solved as of 3.2. The following are the details of how to take advantage of the new test improvements. To ensure that a servlet context is loaded for your test, you need to annotate your test with #WebAppConfiguration and define AnnotationConfigWebContextLoader as your context loader, as below:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(
classes = MyWebConfig.class,
loader = AnnotationConfigWebContextLoader.class)
public class MyTest {
//...
}
If #EnableWebMvc annotation require ServletContext then I suggest to split your config to beans definitions which will be used in unit tests and other configuration which used by application and framework. In this case application will import both configs and unit tests will import only one.
BeansConfig.java:
#Configuration
public class BeansConfig {
#Bean
MyBean myBean() {
return new MyBean()
}
}
WebConfig.java:
#Configuration
#EnableWebMvc
#Import(BeansConfig.class)
public class WebConfig extends WebMvcConfigurationSupport {}
TestFail.java:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=BeansConfig.class)
public class TestFail {
#Test
public void test() {}
}
There is a bug in Spring 3.1, you can find the answer in these two issues:
https://jira.springsource.org/browse/SPR-5243
https://jira.springsource.org/browse/SPR-9799
Please let us know if you find a workaround for Spring 3.1, if not we must wait until 3.2 is out there. I have to say that I've just tried it with Spring 3.2.0.M2 and it is still not working for me.
Another recommendation that I have would be to use spring-test-mvc, which internally creates a mock servlet context for the Controller tests to work.
If you want to continue with your approach, you may then have to create your own Spring Context loader that additionally initializes a Mock servlet context - along these lines:
http://tedyoung.me/2011/02/14/spring-mvc-integration-testing-controllers/,
From Spring-test-mvc source

Categories

Resources