I searched quite a lot on the Internet and I cannot find an example of unit testing with a constructor created automatically. I am using Spring for autowire in the values โโfrom the properties file in my application. I want the unit test method to run MyApp.java, but I have a constructor with auto-preparation, so I donโt know how to create an instance of MyApp. Without properties done automatically, I did this in my unit test:
@Test public void testStart() { try{ MyApp myApp = new MyApp(); myApp.start(); } catch (Exception e){ fail("Error thrown") } }
I donโt want to scoff at autowiring, since I need to get values โโfrom the properties file and to further complicate things, I configure everything through annotations. I do not have spring.xml file, application-context.xml or web.xml file. So, how do I start the process of creating / testing the MyApp launch method? I tried adding automatic binding MyApp MYAPP to @RunWith (SpringJUnit4ClassRunner.class), but it throws errors about the inability to load the application context, which is not fixed by implementing ApplicationContextAware on the test class.
Here is MyApp.java
@Component public class MyApp { private static ApplicationContext applicationContext; private static MyAppProperties myAppProperties;
Here is my app.properties file
# Spring Configuration for My application
Here is MyAppProperties.java
@Component public class MyAppProperties implements ApplicationContextAware { private ApplicationContext applicationContext;
Here is MyAppTest.java
@RunWith(SpringJUnit4ClassRunner.class) public class MyAppTest implements ApplicationContextAware{ private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext appContext) { applicationContext = appContext; } @Autowired private MyApp myapp; @Test public void testStart(){ try { if(myapp != null){ myapp.start(); } else{ fail("myapp is null"); } } catch (Exception e) { fail("Error thrown"); e.printStackTrace(); } } }
UPDATE: here is my configuration class
@Configuration @Component public class ApplicationConfig implements ApplicationContextAware { private final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfig.class); private ApplicationContext applicationContext; public ApplicationContext getApplicationContext() { LOGGER.debug("Getting Application Context", applicationContext); return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; }