MockWebServer:llegalStateException:start()已被调用

Ada*_*gyi 4 android-testing mockwebserver

我尝试使用MockWebServer进行测试。

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

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

java.lang.IllegalStateException: start() already called
Run Code Online (Sandbox Code Playgroud)

码:

@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

    }
 }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?.start()仅调用一次,我什至.shutdown()以防万一...我不知道它怎么可能不止一次调用。

提前致谢。

Ada*_*gyi 5

github上的原始示例中,我发现顺序相反。

只需启动服务器,然后设置它的URL。

并且不设置URL,然后启动服务器。

有趣。

  • 您没有设置检索它的 url,这就是为什么您需要首先启动服务器,这样服务器就已经开始侦听 url:port 并且可以将其返回给您。看起来如果您在启动之前检索 url,那么服务器会自动启动以返回 url。 (2认同)