EsxiSshUtil { public static Session getSessionObject( String userName, String password, String hostName, int port, Properties sessionConfig ) { Session session = null; if ( userName != null && !"".equals( userName ) && password != null && hostName != null && !"".equals( hostName ) ) { JSch jsch = new JSch(); try { if ( sessionConfig != null && InbandConstants.STRICT_HOST_KEY_CHECK_YES.equals( sessionConfig.getProperty( InbandConstants.STRICT_HOST_KEY_CHECKING ) ) ) { String fileLocation = InbandProperties.getKnownHostsLocation(); File f = new File( fileLocation ); if ( f.exists() && !f.isDirectory() ) { jsch.setKnownHosts( fileLocation ); } else { logger.debug( "The file: {} for getting .ssh/known_hosts doesn't exist", fileLocation ); throw new FileNotFoundException( "The file: " + fileLocation + " for getting .ssh/known_hosts doesn't exist" ); } } session = jsch.getSession( userName, hostName, port ); session.setPassword( password ); if ( sessionConfig != null ) { session.setConfig( sessionConfig ); } } catch ( Exception e ) { logger.error( "Creating SSH session failed", e ); } return session; } return null; }  static Session getSessionObject( String userName, String password, String hostName, int port,
                                            Properties sessionConfig ); static String executeCommand( Session sessionObj, String command ); static EsxiSshExecResult executeCommandEnhanced( Session session, String command ); static void executeCommandNoResponse( Session sessionObj, String command ); static void upload( Session session, InputStream localInputStream, String remoteFile ); static void download( Session session, OutputStream localOutputStream, String remoteFile ); static SftpATTRS lstat( Session session, String remoteFile ); static String executeCommand( Session sessionObj, String[] commands );  }
@Test public void testGetSessionOnSuccessCase() throws Exception { File fileMock = mock( File.class ); whenNew( File.class ).withArguments( anyString() ).thenReturn( fileMock ); when( fileMock.exists() ).thenReturn( true ); when( fileMock.isDirectory() ).thenReturn( false ); Session session = mock( Session.class ); JSch jsch = mock( JSch.class ); whenNew( JSch.class ).withNoArguments().thenReturn( jsch ); Mockito.doNothing().when( jsch ).setKnownHosts( anyString() ); when( jsch.getSession( anyString(), anyString(), anyInt() ) ).thenReturn( session ); Properties config = new Properties(); config.put( "StrictHostKeyChecking", "yes" ); Session sessionObj = EsxiSshUtil.getSessionObject( "user", "password", "127.0.0.1", 22, config ); assertNotNull( sessionObj ); }