Dangling Piyush
Dangling Piyush

Reputation: 3676

JUnit Test : Forcing exception from internal method call

I am trying to write a test case which covers a piece of code written inside a catch block. This is how it goes:

I have two methods in class A.

class A{

     public SomeReturnType m1()
     {
       try{
            m2();
         }catch(SomeException ex)
         {
          //handler code for SomeException (This is what I want to test). 
         }
     }

     public SomeReturnType m2() throws SomeException
     {
            //Some logic
     }
}

I am wondering How can a force this exception when m2() is called from the unit test case of method m1()? Any solutions using Mockito or any other testing lib?

Upvotes: 3

Views: 4432

Answers (3)

Mureinik
Mureinik

Reputation: 311163

As you suggested, Mockito would be a classic tool for such a usecase:

// Initialization - should probably be in the @Before method:
A a = Mockito.spy(new A());
Mockito.doThrow(new SomeException("yay!")).when(a).m2();

// Actual test:
SomeResult actualResult = a.m1();
assertEquals(someExpectedResult, actualResult); // or some other assertion

The above snippet creates a spyied object (think of it as an anonymous class that extends A) with the defined behavior that when m2() is called, a SomeException will be thrown. Then the code goes on to call the real m1() method, which itself calls m2(), and has to handle the exception.

Upvotes: 3

vrudkovsk
vrudkovsk

Reputation: 363

Of couse partial mock can solve your problem but there is some flaw in the design itself. Your API provides two methods with same signature one with richer exception management functionality. Pattern decorator seem to be more elegant here and no partial mock required to properly test it.

Upvotes: 1

Yosef Weiner
Yosef Weiner

Reputation: 5751

If you're not interested in restructuring this class, the best way would be to use a partial mock. Stub out m2() to throw an exception when called, and then call m1().

Use Mockito to mock some methods but not others

Upvotes: 0

Related Questions