How to execute JUnit test constructor Spring?

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; //Obtain the values from the app.properties file @Autowired MyApp(MyAppProperties myAppProps){ myAppProperties = myAppProps; } public static void main(String[] args) throws Exception { // Instantiate the application context for use by the other classes applicationContext = new AnnotationConfigApplicationContext("com.my.company"); start(); } /** * Start the Jetty server and configure the servlets * * @throws Exception */ public static void start() throws Exception { // Create Embedded Jetty server jettyServer = new Server(); // Configure Jetty so that it stops at JVM shutdown phase jettyServer.setStopAtShutdown(true); jettyServer.setStopTimeout(7_000); // Create a list to hold all of the handlers final HandlerList handlerList = new HandlerList(); // Configure for Http HttpConfiguration http_config = new HttpConfiguration(); http_config.setSecureScheme("https"); http_config.setSecurePort(myAppProperties.getHTTP_SECURE_PORT()); .... } } 

Here is my app.properties file

 # Spring Configuration for My application #properties for the embedded jetty server http_server_port=12345 

Here is MyAppProperties.java

 @Component public class MyAppProperties implements ApplicationContextAware { private ApplicationContext applicationContext; //List of values from the properties files to be autowired private int HTTP_SERVER_PORT; ... @Autowired public MyAppProperties( @Value("${http_server_port}") int http_server_port, ...){ this.HTTP_SERVER_PORT = http_server_port; } /** * @return the applicationContext */ public ApplicationContext getApplicationContext() { return applicationContext; } /** * @param applicationContext * the applicationContext to set */ @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * @param name * the name to set */ public void setHTTP_SERVER_PORT(String name) { JETTY_SERVER_NAME = name; } /** * @return the httpServerPort */ public int getHTTP_SERVER_PORT() { return HTTP_SERVER_PORT; } } 

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; /** * @return the applicationContext */ public ApplicationContext getApplicationContext() { LOGGER.debug("Getting Application Context", applicationContext); return applicationContext; } /** * @param applicationContext * the applicationContext to set */ @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } // Needed for @Value /** * Property sources placeholder configurer. * * @return the property sources placeholder configurer */ @Bean public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() { PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer(); propertyPlaceholderConfigurer.setLocation(new ClassPathResource("app.properties")); return propertyPlaceholderConfigurer; } ... } 
+6
source share
1 answer

We can mock objects using the jmockito framework.

Using @InjectMocks to inject dependencies through Mockito You also have an @InjectMocks annotation that tries to introduce a dependency of a constructor, method, or field based on a type. The following code is a slightly modified example from Javadoc.

 // Mockito can construct this class via constructor public class ArticleManager { ArticleManager(ArticleCalculator calculator, ArticleDatabase database) { } } // Mockito can also perform method injection public class ArticleManager { ArticleManager() { } void setDatabase(ArticleDatabase database) { } void setCalculator(ArticleCalculator calculator) { } } // Mockito can also perform field injection public class ArticleManager { private ArticleDatabase database; private ArticleCalculator calculator; } 

Below will be the unit test class.

 @RunWith(MockitoJUnitRunner.class) public class ArticleManagerTest { @Mock private ArticleCalculator calculator; @Mock private ArticleDatabase database; @Spy private UserProvider userProvider = new ConsumerUserProvider(); // creates instance of ArticleManager // and performs constructor injection on it @InjectMocks private ArticleManager manager; @Test public void shouldDoSomething() { // assume that ArticleManager has a method called initialize which calls a method // addListener with an instance of ArticleListener manager.initialize(); // validate that addListener was called verify(database).addListener(any(ArticleListener.class)); } 

}

Make sure you use @RunWith (MockitoJUnitRunner.class) For more information, see http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/InjectMocks.html .

+6
source

All Articles