How to mock a final class with mockito

后端 未结 25 1535
日久生厌
日久生厌 2020-11-22 16:35

I have a final class, something like this:

public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}

I

25条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 16:56

    Solutions provided by RC and Luigi R. Viggiano together is possibly the best idea.

    Although Mockito cannot, by design, mock final classes, the delegation approach is possible. This has its advantages:

    1. You are not forced to change your class to non-final if that is what your API intends in the first place (final classes have their benefits).
    2. You are testing the possibility of a decoration around your API.

    In your test case, you deliberately forward the calls to the system under test. Hence, by design, your decoration does not do anything.

    Hence you test can also demonstrate that the user can only decorate the API instead of extending it.

    On a more subjective note: I prefer keeping the frameworks to a minimum, which is why JUnit and Mockito are usually sufficient for me. In fact, restricting this way sometimes forces me to refactor for good as well.

提交回复
热议问题