我想在使用RetroFit
和时模拟无网络案例MockWebServer
.
我正在测试使用Espresso
和提供MockWebServer
s url到RestAdapter
我开始测试之前.这非常适合模拟服务器响应等等,但是我无法看到一种简单的方法来编写java.net.ConnectException
设备没有网络时引发的异常的脚本.我可以看到MockResponse允许限制模拟等,但不是自定义异常.
我知道我可以嘲笑使用的实际web api接口,retrofit
但是如果可能的话,我想使用与其他测试相同的方法MockWebServer
.
我想我只是错过了一些简单的东西:)
谢谢
使用Robolectric 2.3-SNAPSHOT,我想测试一个在后台执行请求的对象.为了隔离它,我试图模拟返回的HttpResponse,在投入几个小时后没有成功.
我创建了一个任何人都可以克隆的项目.模拟运行./gradlew检查 https://github.com/Maragues/RobolectricDummyProject(git clone https://github.com/Maragues/RobolectricDummyProject.git)
我试过了
Robolectric.setDefaultHttpResponse(200,"my_mocked_word");
MockWebServer(https://code.google.com/p/mockwebserver/)
但测试失败是因为他们查询真实的URL
private static final String MOCKED_WORD = "MOCKED";
@Test
public void mockedRequestUsingMockServer() throws Exception {
mMockWebServer.enqueue(new MockResponse().setBody(MOCKED_WORD));
mMockWebServer.play();
Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
Robolectric.getFakeHttpLayer().interceptResponseContent(false);
String result = request.loadDataFromNetwork();
assertEquals(MOCKED_WORD, result);
}
@Test
public void mockedRequestUsingRobolectric() throws Exception {
Robolectric.setDefaultHttpResponse(200, MOCKED_WORD);
String result = request.loadDataFromNetwork();
assertEquals(MOCKED_WORD, result);
}
Run Code Online (Sandbox Code Playgroud)
执行请求的代码
public String loadDataFromNetwork() throws Exception {
// With Uri.Builder class we can build our url is a safe manner
Uri.Builder uriBuilder = Uri.parse("http://robospice-sample.appspot.com/reverse").buildUpon(); …
Run Code Online (Sandbox Code Playgroud) 我使用RESTMock我的仪器测试,但只有当我设置工作usesCleartextTraffic
要true
在我的清单。不过,我只希望仪器测试也是如此。有没有办法做到这一点?
我尝试在androidTest
文件夹中创建一个新的清单文件。测试运行,但它们像usesCleartextTraffic
仍然一样失败false
。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package">
<application android:usesCleartextTraffic="true" />
</manifest>
Run Code Online (Sandbox Code Playgroud)
我知道 RESTMock 从版本 0.3.2 开始支持 https,但我宁愿不必处理它。我实际上遵循了他们的指南,最终得到了 OkHttp3 的这个错误:
java.lang.AssertionError: java.security.NoSuchAlgorithmException: The BC provider no longer provides an implementation for KeyPairGenerator.RSA. Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.
有任何想法吗?
我按照这个答案并将我创建的这个清单移动到debug
源文件夹,然后它就可以工作了。现在该android:usesCleartextTraffic="true"
选项仅适用于我的调试版本,由仪器测试使用,因此它可以工作,但它仍然不是正确的解决方案。
android android-espresso mockwebserver android-instrumentation
我在Android JUnit测试中使用MockWebServer库.我正在测试一个调用服务器的SDK.所以我正在使用MockWebServer
覆盖这些服务器URL并捕获SDK发送的内容以对其进行断言.
我遇到的问题是,如果我尝试server.takeRequest()
将其分配给一个新RecordedRequest
变量,那么测试会挂起第二个server.takeRequest()
,有时甚至是第一个 - 如果我在模拟器上运行它会挂起第server.takeRequest()
一种方法,但如果我在我的物理Android设备上运行它,它会冻结第二种方法server.takeRequest()
方法.
public void testSomething() {
final MockWebServer server = new MockWebServer();
try {
server.play();
server.enqueue(new MockResponse().setBody("")
.setResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR));
server.enqueue(new MockResponse().setBody("")
.setResponseCode(HttpURLConnection.HTTP_OK));
server.enqueue(new MockResponse().setBody("")
.setResponseCode(HttpURLConnection.HTTP_OK));
URL url = server.getUrl("/");
// This internal method overrides some of the hardcoded URLs
// within the SDK that I'm testing.
Util.overrideUrls(url.toString())
// Do some server calls via the SDK utilizing the mock server url.
RecordedRequest requestFor500 = server.takeRequest(); …
Run Code Online (Sandbox Code Playgroud) 我想模拟MockWebServer的网络通信.不幸的改造回调永远不会被调用.我的代码:
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(200).setBody("{}"));
server.play();
RestAdapter restAdapter = new RestAdapter.Builder().setConverter(new MyGsonConverter(new Gson()))
.setEndpoint(server.getUrl("/").toString()).build();
restAdapter.create(SearchService.class).getCount(StringUtils.EMPTY,
new Callback<CountContainer>() {
@Override
public void success(CountContainer countContainer, Response response) {
System.out.println("success");
}
@Override
public void failure(RetrofitError error) {
System.out.println("error");
}
});
server.shutdown();
Run Code Online (Sandbox Code Playgroud)
当我在没有回调的情况下使用改装时,它可以工作.
我正在尝试使用Espresso
和为我的 Fragments 编写 UI 测试MockWebServer
。我OkHttp Idling Resource
用来告诉 Espresso 等待 API 调用完成。
但不知何故,有时我的测试有效,但有时无效,因为Espresso
在服务请求之前就完成了它的工作。所以我的 recyclerView 项目点击测试失败。
我不明白为什么 espresso 不等待 API 调用?任何人都可以帮忙吗?
这是我的测试课
@MediumTest
@HiltAndroidTest
@UninstallModules(PersistenceModule::class, NetworkModule::class)
class MainFragmentTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
private val mockWebServer = MockWebServer()
@Inject
lateinit var okHttp3IdlingResource: OkHttp3IdlingResource
@Before
fun setUp() {
hiltRule.inject()
// Prepare Mock Web Server
mockWebServer.start(8080)
IdlingRegistry.getInstance().register(okHttp3IdlingResource)
}
@Test
fun mainFragmentTest(){
// Prepare Mock Web Server
mockWebServer.dispatcher = object : Dispatcher() {
override fun dispatch(request: …
Run Code Online (Sandbox Code Playgroud) 我正在使用spring-boot
with WebClient
,它作为 bean 自动装配。
问题:在编写junit
集成测试时,我必须使用 okhttp MockWebServer
。此模拟始终在随机端口上启动,例如localhost:14321
.
现在我WebClient
当然有一个固定的网址,它将请求发送到。该 url 可能由application.properties
类似的参数给出webclient.url=https://my.domain.com/
,因此我可以在junit
测试中覆盖该字段。但只是静态的。
问题:如何WebClient
在 a 中重置bean,@SpringBootTest
以便它始终将请求发送到我的模拟服务器?
@Service
public class WebClientService {
public WebClientService(WebClient.Builder builder, @Value("${webclient.url}" String url) {
this.webClient = builder.baseUrl(url)...build();
}
public Response send() {
return webClient.body().exchange().bodyToMono();
}
}
@Service
public void CallingService {
@Autowired
private WebClientService service;
public void call() {
service.send();
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyWebTest …
Run Code Online (Sandbox Code Playgroud) 我们如何使用 MockWebServer 测试应该抛出异常的挂起函数?
fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {
// GIVEN
mockWebServer.enqueue(MockResponse().setResponseCode(500))
// WHEN
val exception = assertThrows<RuntimeException> {
testCoroutineScope.async {
postApi.getPosts()
}
}
// THEN
Truth.assertThat(exception.message)
.isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}
Run Code Online (Sandbox Code Playgroud)
postApi.getPosts()
直接在内部调用 assertThrows
是不可能的,因为它不是一个挂起函数,我尝试使用async
,launch
和
val exception = testCoroutineScope.async {
assertThrows<RuntimeException> {
launch {
postApi.getPosts()
}
}
}.await()
Run Code Online (Sandbox Code Playgroud)
org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown.
但每个变体的测试都会失败。
当我执行mockwebserver.shutdown()时,我收到此错误java.io.ioexception放弃等待执行器关闭。我可以在调试跟踪中看到服务器几乎没有导致错误的活动线程。有没有办法检查并等待活动线程?
mockwebserver ×10
android ×8
retrofit ×3
java ×2
mocking ×2
okhttp ×2
dagger-hilt ×1
junit ×1
okhttp3 ×1
robolectric ×1
spring ×1
spring-boot ×1
testing ×1
unit-testing ×1