jmockit static method

Mockup always comes to us when we try to break system dependency. The conventional mockup frameworks only allowed us to mock instance methods. So the static methods usually become to the death of testability.

Of course, we still have some way to make it become testable.

1. If the static methods invoke only happens in few classes, we could create an adaptor to isolate them. The implementation of adaptor is just simply delegation.

2. Unfortunately, sometimes your legacy system maybe full of static methods calling, they scatter in different tiers.

It indeed a bad smell, but before you refactor them, you may need to make them testable firstly. Now, jmockit comes to us.



"Tests can easily be written that will mock final classes, static methods, constructors, and so on. There are no limitations."

-- jmockit



The following example shows its ability to mock static methods.

//src file

public class ServiceFactory {

public static String getAService() {

return "real service";

}

}



//test file

import mockit.Mock;

import mockit.Mockit;

import static org.junit.Assert.assertEquals;

import org.junit.Test;


public class ServiceFactoryTest {

@Test

public void should_return_mock_service() {

Mockit.setUpMock(ServiceFactory.class, ServiceFactoryStub.class);

assertEquals("mock service", ServiceFactory.getAService());

}


private static class ServiceFactoryStub {

@Mock

public static String getAService() {

return "mock service";

}

}

}





Caution:

Make sure jmockit.jar appears before any JUnit jar file in the classpath. Otherwise, it will shows warning:

"WARNING: JMockit was initialized on demand, which may cause certain tests to fail;
please check the documentation for better ways to get it initialized."
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值