0

Config class with below configuration will load all the required classes in the application as beans by component scan during startup of application as below:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"package1","package2"}
public MvcConfig implements WebMvcConfigurer {

}

How to load the webapplication context inside my junit integration test ? tried below code already which is not working:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MvcConfig.class })
public class ITtest {

    @Autowired
    private ApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) this.wac).build();
    }

 }   

I need to create a mockMVC instance with the web Application context as shown in my setup method.

What is the problem with my code. I expect the context to get loaded with all the classes obtained by package scan of MvcConfig class in my junit integration test.

Vishnu300
  • 126
  • 2
  • 11

1 Answers1

0

@WebAppConfiguration is a class-level annotation that is used to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext. The presence of @WebAppConfiguration on a test class indicates that a WebApplicationContext should be loaded for the test using a default for the path to the root of the web application. To override the default, specify an explicit resource path via the value attribute.

@WebAppConfiguration Sample

Barath
  • 5,093
  • 1
  • 17
  • 42
  • Now the MvcConfig.class is found and junit is trying to load classes present in component scan. But it's failing with error when code is using to get some properties using RealTimePropertyInstance. What are the changes to be made to include jars and properties to build path of junit integration test to run successfully. – Vishnu300 Feb 02 '19 at 09:40
  • You can @TestPropertySources to load the properties. Maven takes care of jars dependency. – Barath Feb 02 '19 at 11:32
  • @Bharat we use Gradle. Do I need to add jars also to the test path for integration tests to work by specifying as dependencies as testcompile or testRruntime in drpendencies section of build.gradle file – Vishnu300 Feb 02 '19 at 11:38
  • Whatever be the case, if the jars are not added in build Gradle. Add it in test scope , build configuration tool will ensure jars are in classpath while running the tests – Barath Feb 02 '19 at 11:39