11

I try to run a test with MockWebServer.

I would like to make a UI test with mocked response, so I could test for valid\invalid UI changes like logging in, or showing error in a login API.

However, each and every time I ran the code I got the following exception:

java.lang.IllegalStateException: start() already called

Code:

@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

    }
 }

What am I doing wrong? The .start() only called once, I even .shutdown() just in case... I don't understand how could it called more than once.

Thanks in advance.

Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222

1 Answers1

20

In the original example at github I have found that the order is reversed.

You actually start the server, THEN sets it's url.

And not setting the url then starting the server.

Interesting.

Adam Varhegyi
  • 11,307
  • 33
  • 124
  • 222
  • 3
    You don't set the url you retrieve it and that's why you need to start the server first, in such a way that the server has already started listening to a url:port and it can return it to you. It looks like if you retrieve the url before starting then the server starts itself automatically to be able to return the url. – kingston Dec 17 '19 at 08:27