Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockWebServer: llegalStateException: start() already called

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 = "[email protected]";
        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.

like image 698
Adam Varhegyi Avatar asked Jan 31 '18 11:01

Adam Varhegyi


1 Answers

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.

like image 199
Adam Varhegyi Avatar answered Oct 15 '22 09:10

Adam Varhegyi