mardi 30 décembre 2014

Mockito object methods of another class

Hi i request your help for know how emulate the method of the class "Validator.validateConnection();" The problem is that the method is validateConnection not exist in the class Class_Implementation and i don't want create that method in the class Class_Implementation. The method validateConnection do a connection to the data base for know if the connection is alive. When mockito runs i get an java.Lang.NullPointerException and is caused by NamingException need to specify class name in enviroment.


The real problem is when i call in the mockito test the line : Boolean resp = mockImpl.checkConnection(); in the checkConnection() the class Validator.validateConnection(); is trying to connect to data base i just want emulate this line and return true or false, but the problem is that the method validateConnection() is an instance of class Validator.


If need more information for fix this please let me know.



public class Class_Implementation {

public boolean checkConnection(){

boolean isConnectionalive = false;

Validator.validateConnection();

// another things for do

return false;

}

}

public class Validator {

public static Boolean validateConnection(){


Connection conn = new Connection();

Boolean connectionAlive = false ;
connectionAlive = conn.isConnectionAlive();

if (connectionAlive){

return true;
}else{

return false;

}
}

}


public class Connection {



public boolean isConnectionAlive(){


// Code for connection to DB
}

}

// class for do the test
@RunWith(PowerMockRunner.class)
@PrepareForTest({Class_Implementation.class,Validator.class})
public class TestConnection {

@Test
public void validate_Connection() throws Exception{



Class_Implementation mockImpl = PowerMock.createPartialMock(Class_Implementation.class);

PowerMock.mockStatic(Validator.class);


PowerMockito.when(mockImpl, Validator.validateConnection() ).thenReturn(true);

PowerMock.replayAll(mockImpl);


Boolean resp = mockImpl.checkConnection();

PowerMock.verifyAll();

Validate.notNull(resp);


}


}


Aucun commentaire:

Enregistrer un commentaire