java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted() while using Mockito with Junit

Sourabh picture Sourabh · May 20, 2014 · Viewed 23.5k times · Source

I am trying to get my feet wet with TDD. I am trying to write unit test cases for controllers using Mockito in conjunction with MockMvc and Junit.

But I am getting a runtime error thereby failing my test. At first I was facing problem in initializing the MockMvc instance in the setup due to failure in finding the javax.servlet.SessionCookieConfig.

This I resolved by downloading the javax.servlet api and configuring it into the build path of the project but then I am facing the

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()

while using perform() on the MockMvc instance.

Can anyone tell me what to do with this kind of dependencies as I think it is occurring due to the incompatible server servlet-api and javax.servlet api.

EDIT : I am posting the code I am using using for unit testing but I don't think it would be any help but just in case :

@RunWith(MockitoJUnitRunner.class)
public class MyControllerTest {

    @InjectMocks
    private MyController myController = new MyController();

    @Mock
    private MyService myService = new MyServiceImpl();

    private MockMvc mockMvc;

    @Before
    public void setUp(){
        this.mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
    }

    @Test
    public void testList() throws Exception{
        A a = new A();
        a = createMockClassA();

        Mockito.when(myService.getServiceForA(Mockito.anyMapOf(String.class, String.class))).thenReturn(a);

        MvcResult result = this.mockMvc.perform(get("/somePath/")).param("someExpectedParam","value").andReturn(); 

        System.out.println(result.getResponse().getContentAsString());

    }



    private static A createMockClassA(){
        A a = new A();
        a.setId(i);
        a.setTitle("mock-" + i);
        return a;
    }
}

Answer

Jens Schauder picture Jens Schauder · May 20, 2014

This sounds very much like you have the wrong version of the servlet API in the class path.

Check when isAsyncStarted was added to the API and make sure the one you reference in your classpath is at least that version or higher.

In order to find the location where the 'wrong' class version is comming from you can use the

-verbose:class

Argument for java. It will list all the classes loaded and if I remember correctly whery they get loaded from. See http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html for details.