【问题标题】:MockWebServer: llegalStateException: start() already calledMockWebServer:非法状态异常:已调用​​ start()
【发布时间】:2018-07-10 12:24:42
【问题描述】:

我尝试使用MockWebServer 运行测试。

我想使用模拟响应进行 UI 测试,因此我可以测试有效\无效的 UI 更改,例如登录,或在登录 API 中显示错误。

但是,每次我运行代码时,我都会遇到 以下异常:

java.lang.IllegalStateException: start() already called

代码:

@RunWith(AndroidJUnit4.class)
public class UITestPlayground {

    String testUrl = "http://testurl.com/";
    MockWebServer server = new MockWebServer();

    @Rule
    public IntentsTestRule<LoginActivity> mIntentsRule = new IntentsTestRule<>(LoginActivity.class);

    @Before
    public void beforeHelper() throws IOException {
        TestHelper.removeUserAndTokenIfAny(mIntentsRule.getActivity());
        URLS.baseUrl = testUrl;
        server.url(URLS.baseUrl);
        //try to shutting down the server JUT IN CASE...
        server.shutdown();
        server.start();

    }

    @After
    public void afterHelper() throws IOException {
        server.shutdown();
    }


    @Test
    public void invalidLoginDueNotValidJSONResponse() {

        server.enqueue(new MockResponse().setBody("Something not valid JSON response"));

        String emailToBeTyped = "tester@tester.com";
        String passToBeTyped = "passtest";

        ViewActions.closeSoftKeyboard();
        // Type text and then press the button.
        onView(withId(R.id.login_email_edit)).perform(typeText(emailToBeTyped));
        ViewActions.closeSoftKeyboard();
        onView(withId(R.id.login_pass_edit)).perform(typeText(passToBeTyped));
        ViewActions.closeSoftKeyboard();
        onView(withId(R.id.log_in_btn)).perform(click());

        //TODO: check on valid error message appearing

    }
 }

我做错了什么? .start() 只调用了一次,我什至 .shutdown() 就在 案例...我不明白它怎么会调用不止一次。

提前致谢。

【问题讨论】:

    标签: android-testing mockwebserver


    【解决方案1】:

    github 的原始示例中,我发现顺序颠倒了。

    实际启动服务器,然后设置它的 url。

    而不是设置 url 然后启动服务器。

    有趣。

    【讨论】:

    • 你没有设置你检索它的 url,这就是为什么你需要先启动服务器,这样服务器已经开始监听一个 url:port 并且它可以返回它给你。看起来如果您在启动之前检索 url,那么服务器会自动启动以能够返回 url。
    猜你喜欢
    • 1970-01-01
    • 2013-01-13
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    相关资源
    最近更新 更多