How to write junit test for graceful shutdown in spring boot - junit4

I'm new to code coverage. I have started to write test cases for my spring boot application.
The below highlighted part in red, I'm unable to cover. Could you please suggest how to test these?
Here is my code.
#SpringBootApplication
public class ImsApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ImsApplication.class);
}
public static void contextDestroyed(ConfigurableApplicationContext ctx) {
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
#Override
public int getExitCode() {
return 0;
}
});
System.exit(exitCode);
}
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(ImsApplication.class, args);
contextDestroyed(ctx);
}
public ImsApplication() {
super();
setRegisterErrorPageFilter(false);
}
#PostConstruct
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
}
}

Related

How to add a hook to the Vertx Launcher

I would like to collect metrics with Vert.x Micrometer Metrics, so I need to set proper options to VertxOptions. I run Vertx with Launcher and there is a hook beforeDeployingVerticle but when I override it it's not called.
I overriden Launcher class and beforeDeployingVerticle method but this method is never executed.
public class LauncherTest {
public static class SimpleVerticle extends AbstractVerticle {
#Override
public void start(Future<Void> startFuture) throws Exception {
System.out.println("verticle started");
}
}
public static class LauncherWithHook extends Launcher {
#Override
public void beforeDeployingVerticle(DeploymentOptions deploymentOptions) {
System.out.println("before deploying");
}
}
public static void main(String[] args) {
new LauncherWithHook().execute("run", SimpleVerticle.class.getName());
}
}
In a result I receive just verticle started, but I expect also to have before deploying there. Should I add this hook somehow different?
change your main method like this:
public static void main(String[] args) {
String[] argz = {"run", "your.namepace.LauncherTest$SimpleVerticle"};
LauncherWithHook launcher = new LauncherWithHook();
launcher.dispatch(argz);
}

Gwtp Autobean and rest

I have InfraNameModel (Rest-type) to work with JSON
public interface IInfraNameBeanFactory extends AutoBeanFactory {
IInfraNameBeanFactory INSTANCE = GWT.create(IInfraNameBeanFactory.class);
AutoBean<InfraNameModel> infraName();
AutoBean<InfraNameListModel> results();
}
public interface InfraNameListModel {
List<InfraNameModel> getResults();
void setResults(List<InfraNameModel> results);
}
public class InfraNameListModelImpl implements InfraNameListModel {
private List<InfraNameModel> results;
#Override
public List<InfraNameModel> getResults() {
return results;
}
#Override
public void setResults(List<InfraNameModel> results) {
this.results = results;
}
}
public interface InfraNameModel {
String getInfraName();
void setInfraName(String infraName);
}
public class InfraNameModelImpl implements InfraNameModel {
private String infraName;
#Override
public String getInfraName() {
return infraName;
}
#Override
public void setInfraName(String infraName) {
this.infraName = infraName;
}
}
I wanted to make them into a separate JAR
To make it common for the client and the server
But now I have errors
[WARN] Class by.models.infraNameModel.InfraNameModel is used in Gin, but not available in GWT client code.
Is it real to pull such beans into a separate library?

How to create an instance of A class that extends Application

I just designed a simple javaFx app. While running it solo works, but when I try to separated and create an instance of it all I get :
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
my code
import javafx.application.Application;
import javafx.stage.Stage;
public class Demo
{
public static void main(String[] args)
{
Demos dm = new Demos();
}
}
class Demos extends Application {
private String args;
private Stage stage;
public Demos()
{
main(args);
start(stage);
}
public void main(String args)
{
this.args=args;
launch(this.args);
}
#Override
public void start(Stage stage)
{
this.stage=stage;
this.stage.setTitle("Simple JavaFX Application");
this.stage.setResizable(false);
this.stage.show();
}
}
Application.launch requires the Application class to be lauched to be public. This is not the case for your Demos class.
Additional Notes
private String args;
private Stage stage;
public Demos()
{
main(args);
...
}
public void main(String args)
{
this.args=args;
...
}
Just assigns the initial value of args to itself, which will always result in args remaining null.
Application.launch is a static method creating the Application instance itself. Calling this form from a instance makes little sense.
If you want to launch a specific Application, pass the Application class to Application.launch:
public static void main(String[] args) {
Application.launch(Demos.class);
}
public Demos extends Application {
private Stage stage;
public Demos(){
}
#Override
public void start(Stage stage) {
this.stage=stage;
this.stage.setTitle("Simple JavaFX Application");
this.stage.setResizable(false);
this.stage.show();
}
}

Customized itemreader throwing ReaderNotOpenException

I have a customized item reader as shown below
class MyReader implements ItemReader<MyBean>, ItemStream{
SingleItemPeekableItemReader<MyBean> myBeanPeekableReader;
public SingleItemPeekableItemReader<MyBean> getMyBeanPeekableReader() {
return myBeanPeekableReader;
}
public void setMyBeanPeekableReader(
SingleItemPeekableItemReader<MyBean> myBeanPeekableReader) {
this.myBeanPeekableReader = myBeanPeekableReader;
}
#Resource
public void caller(ItemReader<MyBean> myJdbcReader){
myBeanPeekableReader.setDelegate(myJdbcReader);
}
#Override
public void close() throws ItemStreamException {
myBeanPeekableReader.close();
}
#Override
public void open(ExecutionContext arg0) throws ItemStreamException {
myBeanPeekableReader.open(arg0);
}
#Override
public void update(ExecutionContext arg0) throws ItemStreamException {
// TODO Auto-generated method stub
}
Class extending JdbcCursorItemReader:
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("myJdbcReader")
public class MyJdbcReader extends JdbcCursorItemReader<MyBean> {
private String sql = "Select * from mytable";
MyJdbcReader(){
super.setSql(sql);
}
#Override
#Resource
public void setDataSource(DataSource dataSource){
super.setDataSource(dataSource);
}
#Override
#Resource
public void setRowMapper(RowMapper myRowMapper){
super.setRowMapper(myRowMapper);
}
#Override
#Resource
public void setPreparedStatementSetter(PreparedStatementSetter myPrepSetter){
super.setPreparedStatementSetter(myPrepSetter);
}
}
Even after implementing ItemStream it is throwing exception ReaderNotFound..can someone suggest where I am getting wrong.

Junit to test restful service

I have written a junit to test my rest service offline.The junit for my restful controller extends AbstractControllerTestSupport which is used to create the dispatcherservletinstance.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader=MockWebContextLoader.class, locations={"/rest-servlet- test.xml"})
public abstract class AbstractControllerTestSupport extends TestCase {
private static DispatcherServlet dispatcherServlet;
....
public static DispatcherServlet getServletInstance() {
if(null == dispatcherServlet) {
dispatcherServlet = new DispatcherServlet() {
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
return MockWebContextLoader.getInstance();
}
};
System.out.println("dispatcher:"+dispatcherServlet.getContextConfigLocation()+":"+dispatcherServlet.getWebApplicationContext());
try {
dispatcherServlet.init(new MockServletConfig());
} catch (ServletException se) {
System.out.println("Exception"+se.getMessage());
}
}
return dispatcherServlet;
}
Following is my loader class.
public class MockWebContextLoader extends AbstractContextLoader {
public static final ServletContext SERVLET_CONTEXT = new MockServletContext(
"/mHealthAPIs", new FileSystemResourceLoader());
private final static GenericWebApplicationContext webContext = new GenericWebApplicationContext();
protected BeanDefinitionReader createBeanDefinitionReader(
final GenericApplicationContext context) {
return new XmlBeanDefinitionReader(context);
}
public final ConfigurableApplicationContext loadContext(
final String... locations) throws Exception {
SERVLET_CONTEXT.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
webContext);
webContext.setServletContext(SERVLET_CONTEXT);
createBeanDefinitionReader(webContext).loadBeanDefinitions(locations);
AnnotationConfigUtils.registerAnnotationConfigProcessors(webContext);
webContext.refresh();
webContext.registerShutdownHook();
return webContext;
}
public static WebApplicationContext getInstance() {
return webContext;
}
protected String getResourceSuffix() {
return "-context.xml";
}
the test runs fine with spring version 3.0 .However if I shift to spring 3.2.x it gives me following error "The type MockWebContextLoader must implement the inherited abstract method SmartContextLoader.loadContext(MergedContextConfiguration)" .This is because in 3.2.2 "AbstractContextLoader" implements "SmartContextLoader" .
Can you provide me with the work around?
Got the solution:I changed the MockWebContextLoader class as follows.
public class MockWebContextLoader extends AbstractContextLoader {
public static final ServletContext SERVLET_CONTEXT = new MockServletContext(
"/mHealthAPIs", new FileSystemResourceLoader());
private final static GenericWebApplicationContext webContext = new GenericWebApplicationContext();
protected BeanDefinitionReader createBeanDefinitionReader(
final GenericApplicationContext context) {
return new XmlBeanDefinitionReader(context);
}
#Override
public ApplicationContext loadContext(MergedContextConfiguration arg0)
throws Exception {
SERVLET_CONTEXT.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
webContext);
webContext.setServletContext(SERVLET_CONTEXT);
createBeanDefinitionReader(webContext).loadBeanDefinitions(
arg0.getLocations());
AnnotationConfigUtils.registerAnnotationConfigProcessors(webContext);
webContext.refresh();
webContext.registerShutdownHook();
return webContext;
}
public static WebApplicationContext getInstance() {
return webContext;
}
protected String getResourceSuffix() {
return "-context.xml";
}
public final ConfigurableApplicationContext loadContext(
final String... locations) throws Exception {
return null;
}
}