假如在测试的时候遇到如下情况:
对于这种想用某个对象一个部分功能,又不想构建完整对象的情况下,就可以用jmock模拟一个对象,模拟对象只需要模拟需要的那部分功能即可
maven
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-junit4</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>org.objenesis</groupId> <artifactId>objenesis</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.jmock</groupId> <artifactId>jmock-legacy</artifactId> <version>2.5.1</version> </dependency> </dependencies>
代码
import junit.framework.Assert; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.jmock.lib.legacy.ClassImposteriser; public class A { @Test public void B() { // 建立一个context上下文对象。(用于mock interfac) Mockery context = new Mockery(); // 生成一个mock对象 final AddressService addressServcie = context.mock(AddressService.class); // 设置期望。 context.checking(new Expectations() { { String s1 = "age"; // 设置期望: addressServcie 对象,调用getAge函数,参数是s1 allowing(addressServcie).getAge(s1); // 设置返回值 will(returnValue("age:11")); String s2 = "name"; oneOf(addressServcie).getName(s2); will(returnValue("name:fang")); } }); // 验证结果 Assert.assertEquals("age:11name:fang", testMockInterface(addressServcie)); //------------------------------------------------------------------------------------ // 建立一个context上下文对象。(用于mock class) final Mockery context1 = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }}; // 生成一个mock对象 final Address address = context1.mock(Address.class); // 设置期望。 context1.checking(new Expectations() { { allowing(address).test(); will(returnValue("test")); } }); // 验证结果 Assert.assertEquals("test", testMockClass(address)); } // 因为传递了一个模拟对象进来,终于让这个函数可以顺利进行测试了 public String testMockInterface(AddressService addressService) { return addressService.getAge("age")+ addressService.getName("name"); } public String testMockClass(Address address) { return address.test(); } } interface AddressService{ String getAge(String age);//{ String getName(String name);//{ } class Address{ public Address(String a){ System.out.println("init"); } public String test(){ return "1"; } }
invocation-count (mock-object).method(argument-constraints); inSequence(sequence-name); when(state-machine.is(state-name)); will(action); then(state-machine.is(new-state-name));