I am testing a function that permit to connect to FTP server.
Here is one of my test who works properly:
#Test
public void connectTestValid()
{
assetSource.setPassword("password");
assetSource.setUsername("user");
assetSource.setServerAddress("127.0.0.1");
assetSource.setServerPort(21);
connectionSuccess = false;
connectionSuccess = ftpFolderTest.connectFTP(ftpClient);
if (!connectionSuccess)
{
fail("Expected Connection success");
}
}
I want to test if the connectFTP() method throw an exception when the serverAddress is invalid.
Here is my test:
#Test(expected = Exception.class)
public void connectTestInvalidServerAddress()
{
assetSource.setPassword("password");
assetSource.setUsername("user");
assetSource.setServerAddress("1");
assetSource.setServerPort(21);
connectionSuccess = false;
connectionSuccess = ftpFolderTest.connectFTP(ftpClient);
}
Here is my function:
protected boolean connectFTP(FTPClient ftp)
{
try
{
ftp.connect(getAssetSource().getServerAddress());
if (!ftp.login(getAssetSource().getUsername(), getAssetSource().getPassword()))
{
logger.error("Login Failed");
ftp.disconnect();
return connectionSuccess = false;
}// if
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
{
logger.error("Connection Failed");
ftp.disconnect();
return connectionSuccess = false;
}// if
}
catch (Exception e)
{
e.printStackTrace();
return connectionSuccess = false;
}
return connectionSuccess = true;
}
Presently, the test doesn't work.
Thanks for your help!
The reason the test is not passing is that it is expecting an Exception to be thrown, but the exception is being caught inside the 'connectFTP' method, which is then returning false.
Whether you return false when connection fails or throw an exception depends on the semantics of your code. Based on the boolean return value, it seems like you're expecting false to be returned when there is an exception. In that case you'll want to do
org.junit.Assert.assertFalse(connectionSuccess);
instead of using (expected = Exception.class) in the #Test annotation.
it looks like you're catching an exception by yourself in your code
If you call the method 'connectFTP' from outside (it doesn't matter whether its a junit or not, it just won't throw an exception.
That's why your JUnit doesn't work.
BTW, it would be better not to work directly with Exception, but with its subtype relevant for your case.
Related
How do I test the catch statement below? My coverlay is failing and I am not sure how to cover this line.
public Method execute(#NonNull final String test) throws ServiceException {
try {
object = javaClient.fetchInfo(test);
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
return object;
}
This is currently what I have in my test file:
#BeforeEach
void setup() {
this.serviceExceptionAdapter = mock(ExceptionAdapter.class);
this.mockJavaClient = mock(JavaClient.class);
proxy = new Proxy(mockJavaClient, serviceExceptionAdapter);
}
#Test
void test_InternalServerError() {
when(mockJavaClient.fetchInfo(any())).thenThrow(InternalServerError.class);
when(serviceExceptionAdapter.apply(any())).thenThrow(ServiceException.class);
assertThrows(ServiceException.class, () -> proxy.execute(test));
verify(serviceExceptionAdapter, times(1)).apply(any());
}
I have to guess a little bit, as you didn't provide a full working example. From what I see in your catch block
} catch (ClientException | InternalServerError e) {
throw serviceExceptionAdapter.apply(e);
}
you expect the return value of your .apply(e) function to be an exception and throw that exception. In your test however, your mocked serviceExceptionAdapter doesn't return an Exception, but throws one instead:
when(serviceExceptionAdapter.apply(any()))
.thenThrow(ServiceException.class);
If my interpretations are correct, your code should work if you change the mentioned line in the test to the following:
when(serviceExceptionAdapter.apply(any()))
.thenReturn(new ServiceException(...));
I have class where I am written code to create a new category and if category not found it will throw "CategoryNotFoundException". I have written the test cases but it was not passed.
If I omit "expected= CategoryNotFoundException.class" from my JUNIT test case it will pass. But I don't want to change any portion in my Test cases. I tried by throwing the exception from my implemented class but still it is not passed.I am stucking there to pass the TestCase.
DAO code::
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
Session session=this.sessionFactory.getCurrentSession();
session.save(category);
return true;
//return isInserted;
}
Tried with the below code as well but TC not passed:
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try{
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
}
catch(Exception ex){
return false;
}
}
JUNIT Code::
#Test(expected= CategoryNotFoundException.class)
#Rollback(true)
public void testCreateCategoryFailure() throws CategoryNotFoundException {
categoryDAO.createCategory(category);
Category savedCategory = categoryDAO.getCategoryById(2);
assertNotEquals(category, savedCategory);`enter code here`
}
You are trying to throw an exception but you are catching also, so you should rethrow If it is necessary, so you should try to do this:
#Transactional
public boolean createCategory(Category category){
//boolean isInserted=false;
try {
Session session=this.sessionFactory.getCurrentSession();
Integer isInsertedWrapper=(Integer)session.save(category);
if(isInsertedWrapper>0){
return true;
}else{
throw new CategoryNotFoundException("CategoryNotFoundException");
}
} catch(CategoryNotFoundException exc) {
throw exc;
} catch(Exception ex){
return false;
}
}
I am new to JUnit and I have to test a method using JUnit api. One method internall calls another. My test case goes inside the method but while catchign the exception it fails.
Method under test is
public void checkANDCondition( Map<String, Message> messagesMap ) throws EISClientException
{
List<String> codes = getMessageCodes();
if(isAllReturnedMessagesContainCodes(codes, messagesMap))
{
StringBuffer buff = new StringBuffer("All of the specified message codes matched returned errors.");
for(String code: codes )
{
Message message = messagesMap.get(code);
buff.append(message.getMessageCode() + ": " + message.getMessageType() + ": " + message.getMessageText() + " ");
}
throw new EISClientException(buff.toString());
}
}
public boolean isAllReturnedMessagesContainCodes(List<String> codes, Map<String, Message> messagesMap)
{
if(codes!=null)
{
for(String code: codes)
{
if(!messagesMap.containsKey(code))
{
return false;
}
}
}
return true;
}
What I have done so far is
#Test
public void testPostProcess() throws Exception {
clientResponse = mock(ClientResponse.class);
MessageToExceptionPostProcessFilter postProcessFilter = new MessageToExceptionPostProcessFilter();
RetrieveBillingServiceResponse serviceResponse = new RetrieveBillingServiceResponse();caughtException = false;
try {
postProcessFilter.setCondition(ConditionOperator.AND);
List<String> messagesCodes = new ArrayList<String>();
messagesCodes.add("200");
messagesCodes.add("400");
Message message = new Message();
message.setMessageCode("200");
message.setMessageType(MessageTypeEnum.MESSAGE_TYPE_INFO);
message.setMessageText("Service completed successfully");
serviceResponse.setMessages(Arrays.asList(message));
postProcessFilter.setMessageCodes(messagesCodes);
serviceResponse = postProcessFilter.postProcess(serviceResponse, clientResponse);
assertNotNull(serviceResponse.getMessages());
} catch (EISClientException ex) {
caughtException = true;
assertEquals("All of the specified message codes matched returned errors.", ex.getMessage());
}
assertTrue(caughtException);
}
How can I make it pass?
Thanks
#Test(expected = EISCLientException.class)
public void testPostProcess() throws Exception {
...
serviceResponse.getMessages();
fail("Shouldn't reach this point");
}
That way you don't need to catch, with expected if it does not get throw a EISClientException it will fail.
edit: There are two times I can think of where you wouldn't want to use this.
1) You are mocking exceptions that are thrown mock(exception.class);
this i believe then throws some Mockito excpetion and it will not match the expected exception.
2) You are wrapping caught exceptions in your code, and throwing a generic exception. Example of code:
try {
} catch (FileParseException e){
throw new (ProjectFailingException(e, "file is bad");
}
if you have multiple catches and are wrapping them as ProjectFailingExceptions then you may want to catch in the test like this...
#Test ( expected = FileParseException.class)
public void testProcess() {
try {
...
} catch (ProjectFailingException e){
throw e.getCause();
}
Then the proper exception is thrown and you can make sure that process isn't throwing an exception from a a different catch.
I have a general query regarding the java programming language and how it deals with exceptions and methods returning boolean.
Please not that although the example below deals with Spring/Ldap/ActiveDirectory, my question is only about java and exceptions.
public boolean doAuthenticate(String userAndDomain, String password) {
UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(replaceBackSlashWithAtSign(userAndDomain), password);
try {
Authentication authentication = adAuthenticationProvider.authenticate(userToken);
return authentication.isAuthenticated();
} catch (BadCredentialsException e) {
log.error("Authentication failed - wrong username\\password", e);
throw new BadCredentialsException("Authentication failed - wrong username\\password", e);
} catch (AuthenticationException e) {
log.error("Authentication failed - AuthenticationException", e);
throw new AuthenticationException("Authentication failed - AuthenticationException", e) { };
}
}
If any of BadCredentialsException or AuthenticationException is rethrown by the authenticate method, then the doAuthenticate method returns false.
However if for some reason another runtime exception is thrown by adAuthenticationProvider.authenticate(), then the method does not return false and does not return at all...
I am just curious to know why that is...
edit:
LdapAuthentifier authentifier = new LdapAuthentifierImpl();
boolean didAuthenticate = authentifier.doAuthenticate(VALID_USER, INVALID_PASSWORD);
A System.out.println of didAuthenticate does show false if one of the two specified exceptions are thrown whereas another exception halts execution of the program and the System.out.println is never reached...
edit 2:
public static void main(String[] args) {
LdapAuthentifier authentifier = new LdapAuthentifierImpl();
boolean didAuthenticate = authentifier.doAuthenticate(VALID_USER, INVALID_PASSWORD);
}
I understand what happened. Here is the explanation.
The exception I actually saw in the logs was BadCredentialsException but this exception is never thrown by adAuthenticationProvider.authenticate and therefore never rethrown by the below method.
What actually happened was that the authentication.isAuthenticated() was just returning false and I was passing this boolean value to the client code.
I am including the method again for clarity's sake:
#Override
public boolean doAuthenticate(String userAndDomain, String password) {
UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(replaceBackSlashWithAtSign(userAndDomain), password);
try {
Authentication authentication = adAuthenticationProvider.authenticate(userToken);
return authentication.isAuthenticated();
} catch (BadCredentialsException e) {
log.error("Authentication failed - wrong username\\password", e);
throw new BadCredentialsException("Authentication failed - wrong username\\password", e);
} catch (AuthenticationException e) {
log.error("Authentication failed - AuthenticationException", e);
throw new AuthenticationException("Authentication failed - AuthenticationException", e) { };
}
}
I am doing Android Unit Test Case Execution and for Negative Test Case I should get exception, but for some API's Exception is not caught.
Please do find the example below:
public void testInsertSenderType_n() {
DBSms obj = new DBSms(getContext());
obj.open();
int i =0;
int a =0;
boolean result = true;
i=obj.GetToatlCount();
obj.insertSmsText(i+1,"Hello to testInsertSenderType_n");
a=obj.TotalcountSms("Inbox");
try
{
obj.insertSenderType(-100, "Richard", "Inbox", 0);
}
catch (Exception e)
{
// TODO: handle exception
result = false;
}
assertEquals(a,obj.TotalcountSms("Inbox"));
assertEquals(false,result);
obj.close();
}
Here in, obj.insertSenderType(-100, "Richard", "Inbox", 0); should throw an exception. But it is not thrown.
Please do guide where can I be Wrong.
I use following method to expect proper exception:
try {
doSomethingToProvokeException();
fail("there ought to be an exception dude, but was not");
} catch(ExeptionIHaveProvoked ex) {
doAssertionnsonThrowsException
}
You do not need variables to keeps exception state. As for why no exception is thrown in your code - nobody cann tell it to you, unless you provide source of object.