9

我尝试使用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()以防万一......我不明白它怎么会调用不止一次。

提前致谢。

4

1 回答 1

16

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

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

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

有趣的。

于 2018-02-01T11:30:14.447 回答