1

I am trying to test the next exception, but I don't know how to throw the exception from JUnit, because is a internal exception of the method.

public boolean suscribirADato(int idDato) { InetAddress ip = null; boolean adecuadamenteSuscrito = false; try { ip = InetAddress.getByName(ipMulticast.get(idDato)); grupoMulticast.set(idDato, ip); conexion.joinGroup(grupoMulticast.get(idDato)); adecuadamenteSuscrito = true; } catch (IOException e) { LOGGER.info(e.getMessage()); } return adecuadamenteSuscrito; } 
3
  • 1
    Use a mocking framework like mockito so that you can throw an exception manually. See: 2min2code.com/articles/mockito_intro/… Commented May 30, 2016 at 14:36
  • Sounds like you need to mock one of the method invocations inside the try block... Commented May 30, 2016 at 14:38
  • Thrown by what, in which circumstances? Commented Jun 4, 2016 at 10:44

2 Answers 2

1

Other replied that you should use a mocking framework.

However, my understanding of your question is the following:

I don't know how to throw the exception from JUnit, because is a internal exception of the method.

What I understand is that you are trying to unit-test an exception thrown and caught inside the method ?

Perhaps your method should be divided into 2 or more methods, which you can test separately ?

From your code sample, the logic being executed when the exception is thrown is

LOGGER.info(e.getMessage()); 

You may also choose to mock LOGGER and keep a trace when info is called. Then, you can assert that LOGGER.info was indeed called (If I understood correctly, that is).

Sign up to request clarification or add additional context in comments.

Comments

1

You need to look into the Mockito framework. http://mockito.org/ when(myMockedObject.routine(anyParameter())).thenThrow(new NullPointerException());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.