spring web 业务系统单测使用Jmockit 进行夸层mock 也可以static 方法mock
来源:互联网 发布:英语在线造句软件 编辑:程序博客网 时间:2024/05/16 02:22
<dependency>
<groupId>com.googlecode.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.5</version>
<scope>test</scope>
</dependency>
现在jmockit已经转入
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.19</version>
</dependency>
spring业务系统一般使用单例. 多层调用. 多层 mock
例如 A调用B,B调用C.
要测试A的方法,需要夸多层mock C的方法.
使用jmockit的NonStrictExpectations
@Servicepublic class A { @Autowired B b; public void method() { b.method(); }}
@Servicepublic class B { @Autowired IC c; public void method() { System.out.println("b=" + c.method()); }}
@Servicepublic class C implements IC { @Override public Integer method() { System.out.println("123"); return 1; }}
public interface IC { public Integer method();}
@RunWith(SpringJUnit4ClassRunner.class)@Transactional@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class })public class JmockitTestMock { @Autowired A a; // 对接口进行mock,对应dubbo @Autowired IC ic; // 夸层 mock.直接把该ic的object引用替换了 @Test public void testMockit() { new NonStrictExpectations(ic) { { ic.method(); //可以对输入进行解析,不同的输入不同的返回. result = Integer.valueOf(5); } }; a.method(); }}
也可以对静态方法进行mock
new NonStrictExpectations(DynamicSettingsUtil.class) { { DynamicSettingsUtil.getString(anyString, anyString); result = "123"; } };
如果(ic)没有传入
new NonStrictExpectations(\) { { ic.method(); result = Integer.valueOf(5); } };
会报如下错误:
java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
方法二:
new MockUp<C>() { @Mock public Integer method() { //可以对输入进行解析,不同的输入不同的返回. System.out.println("MockUp<C> return 6"); return 6; }};
ps: 没有没有@mock, 不会被mock.
方法二,比较智能,即使你获取不到实例. 直接把整个jvm内的class替换掉. 一了百了.
注: 如果遇到执行挺不下来的情况, 死循环的征兆 . 看看 jmockit的classPath顺序是不是比junit后面,如果后面.前把classPath顺序放到前面去.
- spring web 业务系统单测使用Jmockit 进行夸层mock 也可以static 方法mock
- 使用Jmockit完成static方法的mock
- JMockit使用:mock一个类的方法
- 使用easymock进行业务逻辑层测试(使用spring生产mock对象)
- 使用Mock 对spring mvc 的controller层进行单元测试
- jmockit使用(一) —— mock 系统时间
- Mockito结合spring进行跨层 mock
- 单元测试中mock的使用及mock神器jmockit实践
- 单元测试中mock的使用及mock神器jmockit实践
- JMockit Mock 私有方法和私有属性
- Jmockit对类静态方法mock
- 使用 JMockit 来 mock 构造函数
- 使用spring-mock进行dao集成测试
- 使用spring-mock进行dao单元测试
- JMockit 如何 mock 异常
- JMockit主要Mock过程
- 使用mock进行单元测试
- 使用Spring Mock测试Action中的方法
- 调试LATTICE 的SGMII的调试。
- iOS 周刊 第一期
- Maximal Square算法详解
- js 变量 赋予默认值
- 黑马程序员--代码块
- spring web 业务系统单测使用Jmockit 进行夸层mock 也可以static 方法mock
- leetcode-116-Populating Next Right Pointers in Each Node
- iOS周刊第二期
- OpenTLD再续 - 猪肚
- C++ STL中哈希表 hash_map从头到尾详细介绍
- 递归版更相减损术
- BootLoader启动过程
- java.util.vector中的vector的详细用法
- n个骰子的点数