jmock 中unexpected invocation错误

远程服务接口

 

public interface RemoteService {

    public BaseResult findMemberById(Query query);

    public String addMethod();
}

返回值封装对象

 

public class BaseResult {
	
	private String name;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

 服务类

 

public class RealService {

    private RemoteService remoteService;

    public void doExecute(String memberId) {
    	BaseResult apple = null;
    	Query query = new Query(memberId);
    	apple = getRemoteService().findMemberById(query);
        System.out.println(apple);
    }

	public RemoteService getRemoteService() {
		return remoteService;
	}

	public void setRemoteService(RemoteService remoteService) {
		this.remoteService = remoteService;
	}

}

 jmock模拟测试

 

public class RealServiceTest extends TestCase {

    private RealService service = new RealService();

    @Test
    public void testDoExecute() {

        Mockery context = new Mockery();
        final RemoteService remoteService = context.mock(RemoteService.class);
        final BaseResult result = new BaseResult();
        final Query query = new Query("test");
        result.setName("apple");
        
        context.checking(new Expectations() {

            {
                oneOf(remoteService).findMemberById(query);
                will(returnValue(result));
            }
        });

        service.setRemoteService(remoteService);
        service.doExecute("test120");
        context.assertIsSatisfied();
    }

}

 运行报错:

 

 写道
unexpected invocation: morganService.findMemberById()
expectations:
expected once, never invoked: morganService.findMemberById()
parameter 0 did not match: , because was ; returns
what happened before this: nothing!
…………
…………

 观察错误:

com.jmockTest.Query@14a8cd1

com.jmockTest.Query@e0b6f5

有两个Query对象的引用,说明一个问题:Query 这个类被new了两次,RealServiceTest 这个类中new了一次,而RealService 中也new了一次。

jmock使用的代理机制,运行测试类时,参数值不一致,出错。

 

解决方案:http://www.jmock.org/cheat-sheet.html

 

 

有一句话:
To define looser constraints, specify all arguments as matchers within with clauses:

allowing (calculator).add(with(any(int.class)), with(any(int.class)));
 

 

使用: oneOf(remoteService).findMemberById(with(any(Query.class))); 这句解决问题。

 

 

你可能感兴趣的:(J2SE,基础)