2

I have a class as follows:

class Abc{
    static void fun() throws AbcException{
        throw new Exception("Some exception message");
    }
    
    static{
        try{
            fun();
        }catch(AbcException ex){
            ex.printStackTrace();
        }
    }
}

fun() calls some other function and there is a chain of functions following it which throws AbcException if the environment is not configured properly. In Unit Test environment, I faced the AbcException as explained below.

(Also, there are many other methods in this class which I have mentioned)

I want to create an instance of class Abc in my test file. I'm using JUnit 4 and Mockito 4.8.1. I tried the following :

  1. https://github.com/mockito/mockito/issues/2027
  2. https://github.com/mockito/mockito/issues/2390

I wrote my test as follows:

@Before
public void setup(){
    try (MockedStatic<Abc> abc = mockStatic(Abc.class)) {
        // some test setup
    }
}

This didn't help because the AbcException was thrown when mockStatic(Abc.class) was called.

Is there a way to mock Abc class successfully in this case?

  • Tough one - a static initializer block is executed very early, not sure mockito can mock before loading the class... see also https://stackoverflow.com/questions/9130461/when-is-the-static-block-of-a-class-executed – Hulk Nov 28 '22 at 16:22
  • I'm afraid you'll have to use heavier tools for this one - e.g. PowerMock. – Hulk Nov 28 '22 at 16:28
  • Does this answer your question? [Mocking Static Blocks in Java](https://stackoverflow.com/questions/61150/mocking-static-blocks-in-java) – Hulk Nov 28 '22 at 16:28
  • I'm thinking of PowerMock as the second option. Wanted to know if something is possible with mockito first – Karthikeya H S Nov 29 '22 at 03:06
  • What test cases you are going to write? – Kai-Sheng Yang Nov 29 '22 at 05:17
  • I solved this without mocking. I initialised my Unit test environment properly with the application context. – Karthikeya H S Dec 08 '22 at 04:09

1 Answers1

0

For Void methods with Mockito you can :

Simple Mocking and verifying

Argument Capture

Answering a Call to Void

Partial Mocking

Hobbes
  • 111
  • 5