首页 \ 问答 \ 如何学习java设计模式

如何学习java设计模式

更新时间:2024-02-08 17:02

最满意答案

有时我们需要对文件或数据库进行测试,但我们又不想破坏应用程序或设备原有的数据。此时我们就需要一个Mock来替代他们,这里的 Mock不是android.test.mock,但也是android.test包下面的,RenamingDelegatingContext的类。

示例参见:D:\workspace\MockTest
*******************MockContextExampleActivity********
package com.example.mocktest;

import java.io.FileInputStream;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MockContextExampleActivity extends Activity {

public final static String FILE_NAME = "myfile.txt";
private TextView mTv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTv = (TextView) findViewById(R.id.text1);
final byte[] buffer = new byte[1024];
try {
final FileInputStream fis = openFileInput(FILE_NAME);
final int n = fis.read(buffer);
mTv.setText(new String(buffer, 0, n-1));
} 
catch (Exception e) {
mTv.setText(e.toString());
mTv.setTextColor(Color.RED);
}
}

//这里写了个getText方法,测试工程会用到。
public String getText() {
return mTv.getText().toString();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mock_context_example, menu);
return true;
}

}

*****************MockContextExampleTest*****************
package com.example.mocktest;

import android.content.Intent;
import android.test.ActivityUnitTestCase;
import android.test.RenamingDelegatingContext;

public class MockContextExampleTest extends ActivityUnitTestCase {

private static final String PREFIX = "test.";
private RenamingDelegatingContext mMockContext;

public MockContextExampleTest() {
super(MockContextExampleActivity.class);
}

@Override
protected void setUp() throws Exception {
super.setUp();
mMockContext = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), PREFIX);
mMockContext.makeExistingFilesAndDbsAccessible();
}

@Override
protected void tearDown() throws Exception {
super.tearDown();
}

public void testSampleTextDisplayed(){
setActivityContext(mMockContext);
startActivity(new Intent(), null, null);
final MockContextExampleActivity mActivity = getActivity();
assertNotNull(mActivity);
String text = mActivity.getText();
assertEquals("This is *MOCK* data", text);
}
}

Notice:别忘了在清单文件里加上




RenamingDelegatingContext函数的使用,PREFIX是表示文件或数据库的前缀。
另外这里为什么使用getTargetContext方法而不是getContext,后者我们经常在UiTest中使用到。这里其实看下注释就明白了:
//getContext():The instrumentation’s package context.
//getTargetContext(): A Context in the target application.
运行下测试,pass。这说明getText方法返回的string已经是This is *MOCK* data 而不是 This is real data了。这就可以证明,开发没有写死这段话。以上就是RenamingDelegatingContext函数如何来mock文件的,数据库的使用也是一样的。

其他回答

没看懂什么意思?

相关问答

更多
  • 有时我们需要对文件或数据库进行测试,但我们又不想破坏应用程序或设备原有的数据。此时我们就需要一个Mock来替代他们,这里的 Mock不是android.test.mock,但也是android.test包下面的,RenamingDelegatingContext的类。 示例参见:D:\workspace\MockTest *******************MockContextExampleActivity******** package com.example.mocktest; import jav ...
  • 你想测试C类的方法那就直接在C类方法名上右键单元测试就行了啊
  • spring 集成测试中 对mock 的集成实在是太棒了!但是使用请注意一下三个条件。 junit 必须使用四.9以上 同时您的框架必须是用spring mvc spring 三.二以上才完美支持 目前使用spring MVC 取代struts二 的很多,spring MVC 的各种灵活让人无比销魂!所以使用spring MVC吧! 以前在对接口(主要是java服务端提供的接口(一般是:webService,restful))进行测试的中 一般用以下俩种方法
  • 我想出了如何以角度方式解决这个问题。 评论说明了你要做的事情。 //First step: Make sure you included your mock files in the karm conf file //Second step: Define a mock service (function() { 'use strict'; angular.module('mock') .factory('myServiceMock', myServiceMock); f ...
  • 不,您绝对不需要使用数据库 - 您可以自由地实现您想要(或缺少)的任何存储机制。 但是,大多数情况下,您的应用程序中似乎都有一个支持数据库,所以事情会持续存在。 No, you definitely do not need to use a Database -- you are free to implement whatever storage mechanism you want (or lack of). Most of the time, however, it seems you'll have ...
  • 您可以将setupTestFrameworkScriptFile添加到您的jest配置中,以便在所有测试之前运行。 https://facebook.github.io/jest/docs/en/configuration.html#setuptestframeworkscriptfile-string // package.json ... "jest": { "setupTestFrameworkScriptFile": "./src/setupTests.js" } // setupTests.j ...
  • 没关系。 在这两种情况下( 模拟+行为验证 vs 存根+断言 ),您都可以获得完全相同的结果,并且需要完全相同级别的内部工作细节级别。 坚持你认为更适合的情况。 你发布的单元测试是一个行为验证的例子。 您不会断言任何值,而是检查是否调用某个方法。 当方法调用没有可见结果时(考虑日志记录)或不返回任何值(显然)时,这是特别有用的。 它当然有缺点,特别是当你对那些返回值的方法进行这种验证时,并且不检查它(就像你的情况 - 我们会去做的那样)。 存根和断言方法使用协作者来创造价值。 它不检查方法是否被调用(至少不 ...
  • 您应该使用依赖注入模式来规避这一点 After a bit of digging, I found extending ProviderTestCase2 will automatically add a prefix to the database.
  • 因为它们从数据本身中抽象出数据检索 。 对于sqlite数据源,数据在手机上,您可以轻松实现从云服务获取数据的内容提供商。 因此,您可以针对相同的接口进行编码,并轻松切换数据检索实现。 Since they abstracted away the data retrieval from the data itself. While for a sqlite data source, data is on the phone, you can easily implement a content provid ...
  • 您的测试似乎对测试库是正确的,但我相信Mocking对象更适合应用程序测试。 您不希望对您的库测试模型进行模拟,而是在您的应用程序中使用您的库进行测试。 我将举例说明具有单元测试的模拟对象的强大功能。 我刚刚帮助在大量下载的iOS应用程序上编写自动化框架。 我们使用OCMock和KiF来实际自动化应用内容更新。 在我们的自动化测试中,我们使用与应用程序相同的完整代码来执行内容更新。 但是,我们OCMock返回内容URL并让它返回不同的方法。 这非常类似于混合。 现在,应用程序将指向我们的测试URL,以便在测 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)