How can I test final and static methods of a utility project?

I’m trying to implement unit testing for aproject, it uses a legacy “utility” project that is littered with static methods and many of the classes are final or their methods are final. I’m not able to update the legacy project at all.

JMock and EasyMock both choke on final methods, and I don’t see a nice way to test the static calls. What techniques are there to test these?

How can utility classes be used to group methods on a final class, instead of extending the class?

Joshua Bloch mentions in his book (Effective Java – 2nd Ed) in Item 4 :- Classes containing just static fields and static methods (utility classes) can be used to group methods on a final class, inst

How can I test a final class with private constructor?

How can I test a class like this (see code below)? public final class A { public static final String FIRST = 1st; public static final String SECOND = 2nd; private A() { // NOP } } For now all my

static final methods in enum

So I have looked around google and SO , I cannot find a example or explanation of : What is the purpose of static final methods in enum? What I understand : Methods declare static can be accessed lik

Utility class static methods and inheritance

My application has a utility class with static methods which are responsible for showing notifications and optionally sending emails when something bad happens: public static void sendEvent(final Stri

Extension Methods vs Static Utility Class

I’m looking for some pros and cons for using extension methods over static utility classes in a C# app. For instance, a plus in the extension methods column is the convinience of calling by the class

final static methods exam

I have been studying for my Software Development course and came across the question from a sample: Why does it make no sense to have both the static and final modifiers in front of a Java method? I

How can I test void methods? [duplicate]

This question already has an answer here: Unit testing void methods? 9 answers I have some void methods and I need to test them, but I’m not sure about how to do it. I just know how to test met

Creating static utility methods should not be overused however ? how to avoid it? [closed]

With the time …lots of utility method are introduced in java project for more complex and simple task. When using static methods we introduce tight coupling in our code and it make our code more di

How can I extend a static final guava utilities class?

When I’ve used common-collections I’ve done custom extensions to those utils like: class MyCollectionUtils extends CollectionsUtils { static myutilityMethod() static removeDublicate(..) static myPred

Javascript: How can I declare non-global static methods?

How can I declare non-global static methods in js? foo.bar = function() { function testing{ console.log(statckoverlow rocks!); } function testing2{ console.log(testing2 funtction); } } How can I

Answers

If you’re able to refactor your code, you can wrap your calls to the final/static methods in simple instance methods, for example:

protected Foo doBar(String name) {
    return Utility.doBar(name);
}

This allows you to override your wrapper method in the unit test to return a mock instance of Foo.

Alternatively you can use Powermock, which extends Easymock (and Mockito) to allow mocking of final and static methods:

PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.

Here’s an example test mocking a static final method, the example shows how to mock some other types too:

@Test
public void testMockStaticFinal() throws Exception {
    mockStatic(StaticService.class);
    String expected = "Hello altered World";
    expect(StaticService.sayFinal("hello")).andReturn("Hello altered World");
    replay(StaticService.class);

    String actual = StaticService.sayFinal("hello");

    verify(StaticService.class);
    assertEquals("Expected and actual did not match", expected, actual);

    // Singleton still be mocked by now.
    try {
        StaticService.sayFinal("world");
            fail("Should throw AssertionError!");
    } catch (AssertionError e) {
        assertEquals("/n  Unexpected method call sayFinal(/"world/"):", 
            e.getMessage());
    }
}

How about a level of indirection / Dependency Injection?

Since the legacy utility project is your dependency, create an interface to separate it out from your code. Now your real/production implementation of this interface delegates to the legacy utility methods.

public LegacyActions : ILegacyActions
{
  public void SomeMethod() { // delegates to final/static legacy utility method }
}

For your tests, you can create a mock of this interface and avoid interacting with the legacy utility thingie.

If your non-refactorable method uses something like JNDI to connect to another service, I’d consider starting a JDNI service and populating it with stubs which you control. It’s a pain but relatively straightforward. It may mean setting up a database or JMS listener or whatever but there should be a lightweight java implementation you can drop into the tests.

JMockit allows you to mock static methods and final classes. I assume it uses some classloadin-fu, although I haven’t really looked into it.

JMockit Expectations API allows expectations to be set on any kind of method invocation (on interfaces, abstract classes, concrete final or non final classes, and on static methods), as well as on class instantiation through any constructors.

As already pointed out, JMockit can be used. An example:

@Test
public void mockStaticAndFinalMethods(final LegacyService mock)
{
    new NonStrictExpectations()
    {
      {
        LegacyService.staticMethod("hello"); result = "Hello altered World";
      }
    };

    String actual = LegacyService.staticMethod("hello");
    new LegacyService().finalMethod(123, "test");

    assertEquals("Hello altered World", actual);

    new Verifications()
    {
      {
        mock.finalMethod(123, "test"); // verify this call occurred at least once
      }
    };
}

The JMockit project home page contains a comparison with PowerMock, for those interested.

JMock together with JDave can mock final methods and classes, if you need to. Here are instructions. That being said I would treat this legacy code (as others have suggested already) as an external dependency and build interfaces and mock those. It is another layer of indirection, but since you can’t change that legacy code, it seems to be a reasonable one.