問題描述
我正在嘗試使用 TDD.我正在嘗試使用 Mockito 結合 MockMvc 和 Junit 為控制器編寫單元測試用例.
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.
但是我遇到了運行時錯誤,因此我的測試失敗了.起初,由于找不到 javax.servlet.SessionCookieConfig
失敗,我在設置中初始化 MockMvc 實例時遇到了問題.
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
.
我通過下載 javax.servlet
api 并將其配置到項目的構建路徑中解決了這個問題,但隨后我面臨
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()
在 MockMvc 實例上使用 perform()
時.
while using perform()
on the MockMvc instance.
誰能告訴我如何處理這種依賴關系,因為我認為這是由于服務器 servlet-api 和 javax.servlet api 不兼容而發生的.
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;
}
}
推薦答案
這聽起來很像您在類路徑中的 servlet API 版本錯誤.
This sounds very much like you have the wrong version of the servlet API in the class path.
檢查何時將 isAsyncStarted
添加到 API,并確保您在類路徑中引用的版本至少是該版本或更高版本.
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
java 的參數.它將列出所有加載的類,如果我沒記錯的話,它們是從哪里加載的.請參閱 http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html了解詳情.
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.
這篇關于java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted() 將 Mockito 與 Junit 一起使用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!