我有一段代码接受 Context 并将此上下文传递给私有(private)方法。 私有(private)方法调用 getAssets().open() 来读取存在于我的应用程序 Assets 文件夹中的文件。
public void methodA(Context ctx) throws IOException{
// do some stuff here...
Object data[] = getFileContents(ctx);
// use the data[] returned here...
}
private Object[] getFileContents(Context ctx) throws IOException{
Object[] data;
BufferedInputStream is = new BufferedInputStream(context.getAssets().open("test.txt"));
// parse file and create array of Objects[]
return data[];
}
我正在编写单元测试以使用 Mockito 测试 methodA(),以便我可以测试传递垃圾数据或在我的测试用例中抛出异常。
问题是我无法在 Android 中模拟 AssetManager 类(它是 Final)。
我尝试使用 InstrumentationTestCase 注入(inject)真实和测试上下文,但这只适用于少数场景。 我如何控制 BufferedInputStream 以便我可以向它提供我想要的任何输入(使用模拟或其他方式)?
最佳答案
我不得不处理同样的问题。这就是我在不使用 Instrumentation 测试的情况下设法从我的单元测试程序访问配置文件的方法。 (我使用的是 Android Studio 2.1)。
单元测试代码:
public class ParametersTest {
Parameters parameters = null;
@Mock
Context context;
@Mock
AssetManager assetManager;
@Mock
InputStream inputStream;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);//create all @Mock objetcs
doReturn(assetManager).when(context).getAssets();
//parametersandroid.xml is located in test/resources directory
//parametersandroid.xml does not refer to a DTD file configuration.dtd
//get the full path name of the file
URL resource = ParametersTest.class.getClassLoader().getResource("parametersandroid.xml");
// to be used MyClass
// inside the method I want to be tested there is this statement :
// InputStream inputStream = this.assetManager.open(xmlFile);
InputStream inputStream=new FileInputStream(resource.getPath());
doReturn(inputStream).when(assetManager).open(anyString());
// AssetManager assetManager = context.getAssets();
// parameters = new Parameters(assetManager, resource.getPath());
parameters = new Parameters(context, resource.getPath());
}
@Test
public void testExtract() throws Exception {
assertEquals(parameters.extract("//database/index[@name='TeamNameIdx']/create").replaceAll("[^a-z,A-Z,;,.,?,']", ""),"createindexTeamNameIdxonTeamEntnameasc;");
}
}
待测类代码:
public class Parameters extends fr.acnice.valade.eric.gemara.utilities.Parameters {
private AssetManager assetManager = null;
public Parameters(Context context, String xmlFile) {
super(xmlFile);
this.assetManager = context.getAssets();
}
@Override
public String extract(String request) throws XPathExpressionException,
Exception {
InputStream inputStream = this.assetManager.open(super.xmlFile);
String result = (String) xPath.evaluate(request, new InputSource(inputStream),
XPathConstants.STRING);
if (result.isEmpty()) {
throw new Exception(
"Xpath result empty !!! check configuration file");
}
return result;
}
}
关于android - 模拟 Android AssetManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407178/
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路
假设我在Store的模型中有这个非常简单的方法:defgeocode_addressloc=Store.geocode(address)self.lat=loc.latself.lng=loc.lngend如果我想编写一些不受地理编码服务影响的测试脚本,这些脚本可能已关闭、有限制或取决于我的互联网连接,我该如何模拟地理编码服务?如果我可以将地理编码对象传递到该方法中,那将很容易,但我不知道在这种情况下该怎么做。谢谢!特里斯坦 最佳答案 使用内置模拟和stub的rspecs,你可以做这样的事情:setupdo@subject=MyCl
在ruby中,你可以这样做:classThingpublicdeff1puts"f1"endprivatedeff2puts"f2"endpublicdeff3puts"f3"endprivatedeff4puts"f4"endend现在f1和f3是公共(public)的,f2和f4是私有(private)的。内部发生了什么,允许您调用一个类方法,然后更改方法定义?我怎样才能实现相同的功能(表面上是创建我自己的java之类的注释)例如...classThingfundeff1puts"hey"endnotfundeff2puts"hey"endendfun和notfun将更改以下函数定
我有一个gem,它有一个根据Rails.env的不同行为的方法:defself.envifdefined?(Rails)Rails.envelsif...现在我想编写一个规范来测试这个代码路径。目前我是这样做的:Kernel.const_set(:Rails,nil)Rails.should_receive(:env).and_return('production')...没关系,只是感觉很丑。另一种方法是在spec_helper中声明:moduleRails;end而且效果也很好。但也许有更好的方法?理想情况下,这应该有效:rails=double('Rails')rails.sho
我有一个rspec模拟对象,一个值赋给了属性。我正在努力在我的rspec测试中满足这种期望。只是想知道语法是什么?代码:defcreate@new_campaign=AdCampaign.new(params[:new_campaign])@new_campaign.creationDate="#{Time.now.year}/#{Time.now.mon}/#{Time.now.day}"if@new_campaign.saveflash[:status]="Success"elseflash[:status]="Failed"endend测试it"shouldabletocreat
我正在尝试测试命令行工具的输出。如何使用rspec来“伪造”命令行调用?执行以下操作不起作用:it"shouldcallthecommandlineandreturn'text'"do@p=Pig.new@p.should_receive(:run).with('my_command_line_tool_call').and_return('resulttext')end如何创建stub? 最佳答案 使用newmessageexpectationsyntax:规范/虚拟规范.rbrequire"dummy"describeDummy
我有一个或多或少这样的场景classAdefinitialize(&block)b=B.new(&block)endend我正在对A类进行单元测试,我想知道B#new是否正在接收传递给A#new的block。我使用Mocha作为模拟框架。这可能吗? 最佳答案 我用Mocha和RSpec都试过了,虽然我可以通过测试,但行为不正确。从我的实验中,我得出结论,验证block是否已通过是不可能的。问题:为什么要传递一个block作为参数?block将用于什么目的?什么时候调用?也许这确实是您应该用类似的东西测试的行为:classBlockP
我目前正在将一种算法从Java转换为Ruby,但由于Ruby中缺少整数溢出,我遇到了一些障碍。假设我的值为2663860877,它大于最大整数2147483648。在Java中,它环绕,我应该得到-1631106419。我找到了这段代码,但它似乎不起作用:defforce_overflow(i)ifi2147483647i&0xffffffffelseiendend并且'ing变量不会像您期望的那样强制它为负。 最佳答案 假设32位整数具有二进制补码负数,这应该可行:defforce_overflow_signed(i)force_
我有一个命令行应用程序,它使用thor来处理选项的解析。我想使用test-unit和/或minitest针对代码对命令行功能进行单元测试。我似乎无法弄清楚如何确保ARGV数组(通常会保存命令行中的选项)保存我的测试选项,以便它们可以根据代码进行测试。具体应用代码:#myapp/commands/build.rbrequire'thor'moduleMyappmoduleCommands#DefinebuildcommandsforMyAppcommandlineclassBuild:test_unit#Definesourcerootofapplicationdefself.sourc