sotn
sotn

Reputation: 2101

Unit testing that log message written when exception caught

Here is the code that I am working with. In this test I want to verify that the log method is being called when an exception is caught.

public class SuperClass(){
   public void log()
   {
      do some logging;
   }
}

public class ClassUnderTest extends SuperClass(){

    public String methodbeingtested(Object param)
    {
      try
         {
             String a = SomeObject.
                              methodthatthrowsexception(param);//static method, throws JAXB/NPE
         }
      catch(Exception exp)
         {
             log("log msg",exp);//inherited method
         }
    }
}


public class ClassUnderTestTest {

    @Test
    public testmethodbeingtested(){
       ClassUnderTest cut = new ClassUnderTest()
       ClassUnderTest cutspy = Mockito.spy(cut);

       cutspy.methodbeingtested(param);

       Mockito.verify(cutspy).log("log msg", new Exception()); // exp is needed to here.  
    }
}

After looking at several samples, the above was the closest I could get. This testcase forces an exception. But it fails to verify the log method call as Mockito.verify requires the exact exception (exp) that is caught, which the test case does not have access to.

Is there any other way to test this scenario?

Upvotes: 1

Views: 4411

Answers (2)

Rahul
Rahul

Reputation: 13056

Instead of spying on ClassUnderTest, you should mock the logging framework, inject it into the class and then verify that the log method gets called. Id' also mock the SomeObject class and have it throw exception.

As an aside, you should really evaluate if you need to verify your log statements. Perhaps you have a valid reason to do so but typically, asserting/verifying to this extent is not required and will only make your tests brittle.

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

Mockito's verify method can be used with argument matchers. If you want to verify that log was called, with any Exception at all as the second argument, you can just write

verify(cutspy).log(eq("log msg"), any(Exception.class));

I've assumed that you have the right static imports for verify, eq and any.

As an aside, this test does not need PowerMock. Your line PowerMock.expectLastCall().once(); is both redundant and confusing, and should probably be removed, along with the @PrepareForTest annotation.

Upvotes: 2

Related Questions