EasyMock的capture的使用

       EasyMock里面的Capture接口提供了捕获函数调用参数的方法,在mock中,我们要验证参数传递参数的的情况。这个里面可以设置Capture的类型。
       不废话了,直接上代码:
       
import java.util.Locale;

public interface GeographicalDao {
   public void insertLocale(Locale locale);  
}
               


下面是一个service接口
import java.util.Locale;

public class GeographicalService {
	
    private GeographicalDao geographicalDao;  
  
    public void setGeographicalDao(GeographicalDao geographicalDao) {  
        this.geographicalDao = geographicalDao;  
    }  
  
    public void saveGeographical(String language, String country) {  
        geographicalDao.insertLocale(new Locale(language, country));  
    }
}

最后上测试代码:
import java.util.List;
import java.util.Locale;

import org.easymock.Capture;
import org.easymock.CaptureType;
import org.easymock.EasyMock;
import org.junit.Test;

public class GeographicalServiceTest {
	@Test
	public void captureTest(){
		String language = "us";
		String country = "UK";
		
		Capture<Locale> localCapture = new Capture<Locale>(CaptureType.ALL);
		GeographicalDao mock = EasyMock.createMock(GeographicalDao.class);
		mock.insertLocale(EasyMock.capture(localCapture));
		
		EasyMock.expectLastCall().times(2);
		
		EasyMock.replay(mock);
		
		GeographicalService service = new GeographicalService();
		service.setGeographicalDao(mock);
		
		service.saveGeographical(language, country);
		language = "zh";
		country = "CN";
		service.saveGeographical(language, country);
		
		EasyMock.verify(mock);
		
		List<Locale> locales = localCapture.getValues();
		for(Locale local : locales){
			System.out.println(local.getLanguage() + "_" + local.getCountry());
		}
	}



   在这个里面,我们capture所有的函数调用的参数。

你可能感兴趣的:(java,JUnit)