ben
ben

Reputation: 1

How can i make DateUtil throw an exception?


    @Override
        public void contextDestroyed(ServletContextEvent sce) {
            try{
                DateUtil.clean();
            }catch(Exception e){
                LOGGER.error("MyServletContextListener contextDestroyed error: ", e);
            }

I am doing unit testing on the above piece of code, and am trying to get 100% line coverage by hitting the Exception clause, however, i cant seem to make it work with my implementation. Would appreciate any help yall. Please look below for my implementation.

 @Test (expected= Exception.class)
    public void test_contextDestroyed_Exception() {

        DateUtil wrapper = Mockito.spy(new DateUtil());
        Exception e = mock(Exception.class);

        when(wrapper).thenThrow(e);
       Mockito.doThrow(e)
                .when(myServletContextListener)
                .contextDestroyed(sce);

        myServletContextListener.contextDestroyed(sce);
    } 

Upvotes: 0

Views: 221

Answers (2)

prostý člověk
prostý člověk

Reputation: 939

you can use mockito-inline artifact from Mockito to test static methods and follow the below approach,

try (MockedStatic<DateUtil> utilities = Mockito.mockStatic(DateUtil.class)) {
            utilities.when(DateUtil::clean).thenThrow(Exception.class);
            // assert exception here
        }

for more info,

https://frontbackend.com/java/how-to-mock-static-methods-with-mockito

Upvotes: 0

Matteo NNZ
Matteo NNZ

Reputation: 12665

Since DateUtil.clean() is a static method, you can't mock it with Mockito. You need to use PowerMockito instead:

<properties>
    <powermock.version>1.6.6</powermock.version>
</properties>
<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
</dependencies>

Check official PowerMock documentation for version compatibility with JUnit and Mockito.

Once you did that, you should add the following to your test class:

@RunWith(PowerMockRunner.class) //<-- this says to JUnit to use power mock runner
@PrepareForTest(DateUtil.class) //<-- this prepares the static class for mock
public class YourTestClass {
    
    @Test(expected = Exception.class)
    public void test_contextDestroyed_Exception() {
        PowerMockito.mockStatic(DateUtil.class);
        when(DateUtil.clean()).thenThrow(new Exception("whatever you want"));
        //prepare your test
        //run your test:
        myServletContextListener.contextDestroyed(sce);
    }
    
 
}

Upvotes: 1

Related Questions