2015-07-22 14 views
8

Tôi đang cố gắng thực hiện một số thử nghiệm jUnit trong một trong các servlet của tôi nhưng bất cứ khi nào tôi cố gắng chạy nó, tôi nhận được một ExceptionInInitializerError. Tôi đã đọc rằng lỗi này là do một ngoại lệ, xảy ra trong quá trình đánh giá bộ khởi tạo tĩnh hoặc bộ khởi tạo cho một biến tĩnh. Vấn đề là mặc dù tôi đã cố sửa nó nhưng tôi có thể. Đó là lý do tôi viết ở đây: Mã servlet của tôi là như sau:java.util.MissingResourceException: Không thể tìm thấy gói cho tên cơ sở javax.servlet.LocalStrings, locale es_ES

public class AppServlet extends HttpServlet { 

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> 
/** 
* Handles the HTTP <code>GET</code> method. 
* 
* @param request servlet request 
* @param response servlet response 
* @throws ServletException if a servlet-specific error occurs 
* @throws IOException if an I/O error occurs 
*/ 
@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    try { 
     response.setContentType("text/html;charset=UTF-8"); 
     PrintWriter out = response.getWriter(); 

     //obtenemos los valores de los campos del formulario. 
     String usr = request.getParameter("usrName"); 
     String cp = request.getParameter("codigoPostal"); 
     Gson gson = new Gson(); 
     if (usr == null || cp == null || cp.length() != 5) { 
      Result r = new Result("KO", "No se introdujeron bien los datos"); 
      String jsonString = gson.toJson(r); 
      out.println(jsonString); 
      return; 
     } 

     //procedemos a convertir el codigo postal en la ciudad usando geonames: 
     //para ello usaremos la api de geonames 
     String city = geoLocalize.localizeCity(cp); 

     //empezaremos con el codigo de depuración para ver donde podemos tener errores 
     if (city == null) { 
      Result r = new Result("KO", "No hay ciudad para dicho codigo postal"); 
      String jsonString = gson.toJson(r); 
      out.println(jsonString); 
      return; 
     } 
     //comenzamos con las bases de datos 
     SQLconnection db = new SQLconnection(); 
     //una vez creada la conexion deberemos hacer las insert en las tablas. 

     if (!db.checkUsr(usr)) { 
      if (db.insertUsr(usr)) { 
       int numCp = parseInt(cp); 
       if (!db.checkCP(numCp)) { 
        if (db.addCity(numCp, city)) { 
         Result r = new Result("OK", "Proceso terminado sin problemas"); 
         String jsonString = gson.toJson(r); 
         out.println(jsonString); 
         return; 
        } else { 
         Result r = new Result("KO", "No se ha podido añadir la ciudad"); 
         String jsonString = gson.toJson(r); 
         out.println(jsonString); 
         return; 
        } 

       } else { 
        Result r = new Result("OK", "Se ha añadido el usuario, el codigo postal ya estaba"); 
        String jsonString = gson.toJson(r); 
        out.println(jsonString); 
        return; 
       } 
      } else { 
       Result r = new Result("KO", "No se ha podido añadir el usuario"); 
       String jsonString = gson.toJson(r); 
       out.println(jsonString); 
       return; 
      } 

     } else { 
      Result r = new Result("KO", "El usuario ya existe en el sistema"); 
      String jsonString = gson.toJson(r); 
      out.println(jsonString); 
      return; 
     } 

    } catch (IOException | NumberFormatException ex) { 
     Logger.getLogger(AppServlet.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (Exception ex) { 
     Logger.getLogger(AppServlet.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

}

Và mã kiểm tra JUnit của tôi là như sau:

public class AppServletTest extends TestCase { 

HttpServletRequest request; 
HttpServletResponse response; 
AppServlet instance; 

public AppServletTest(String testName) { 
    super(testName); 

} 


@Override 
protected void setUp() throws Exception { 
    request = mock(HttpServletRequest.class); 
    response = mock(HttpServletResponse.class); 
    instance = new AppServlet(); 
    super.setUp(); 
} 


@Override 
protected void tearDown() throws Exception { 
    super.tearDown(); 
} 

/** 
* Test of doGet method, of class AppServlet. 
* 
* @throws java.lang.Exception 
*/ 

public void testDoGet() throws Exception { 
    System.out.println("doGet"); 

    //generamos los parametros y un .txt donde guardaremos la respuesta JSON 
    when(request.getParameter("usrName")).thenReturn("Javi"); 
    when(request.getParameter("codigoPostal")).thenReturn("48991"); 
    PrintWriter writer = new PrintWriter("resultadoPruebas.txt"); 
    when(response.getWriter()).thenReturn(writer); 

    //mandamos la peticion al servlet 
    instance.doGet(request, response); 

    verify(request, atLeast(1)).getParameter("usrName"); // para verificar si se ha llamado a usrName 
    writer.flush(); // it may not have been flushed yet... 
    assertTrue(FileUtils.fileRead(new File("somefile.txt"), "UTF-8") 
      .contains("OK")); 


} 

}

Một ở đây là toàn bộ stacktrace:

java.lang.ExceptionInInitializerError 
at com.jbo.testapp.AppServletTest.setUp(AppServletTest.java:36) 
at junit.framework.TestCase.runBare(TestCase.java:128) 
at junit.framework.TestResult$1.protect(TestResult.java:106) 
at junit.framework.TestResult.runProtected(TestResult.java:124) 
at junit.framework.TestResult.run(TestResult.java:109) 
at junit.framework.TestCase.run(TestCase.java:120) 
at junit.framework.TestSuite.runTest(TestSuite.java:230) 
at junit.framework.TestSuite.run(TestSuite.java:225) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:497) 
at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:96) 
at org.apache.maven.surefire.junit.JUnit3Provider.executeTestSet(JUnit3Provider.java:117) 
at org.apache.maven.surefire.junit.JUnit3Provider.invoke(JUnit3Provider.java:94) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:497) 
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) 
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) 
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) 
at 

org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) 
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) 
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale es_ES 
    at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1564) 
    at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1387) 
    at java.util.ResourceBundle.getBundle(ResourceBundle.java:773) 
    at javax.servlet.GenericServlet.<clinit>(GenericServlet.java:95) 
    ... 24 more 
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale es_ES 
    at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1564) 
    at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1387) 
    at java.util.ResourceBundle.getBundle(ResourceBundle.java:773) 
    at javax.servlet.GenericServlet.<clinit>(GenericServlet.java:95) 
    ... 24 more 

Hy vọng các bạn có thể giúp tôi! Cảm ơn bạn trước

+2

Thêm toàn bộ stacktrace xin vui lòng. – Jens

+0

! đã thêm :) –

Trả lời

21

Nguyên nhân: java.util.MissingResourceException: Không thể tìm thấy bó cho javax.servlet.LocalStrings tên cơ sở, es_ES locale

Đó là lỗi thực sự.

Thử nghiệm đang chạy của bạn thiếu phụ thuộc servlet-api.

Nếu bạn đang sử dụng maven đảm bảo sự phụ thuộc này là trong dự án của bạn:

<dependency> 
    <groupId>javax.servlet</groupId> 
    <artifactId>javax.servlet-api</artifactId> 
    <version>3.1.0</version> 
</dependency> 
+0

Cảm ơn bạn rất nhiều! vấn đề được giải quyết, bạn đã đúng. –

+3

Lạ. Tôi nghĩ rằng 'javax: javaee-api: 7.0' là đủ. – Jarekczek

+0

Bạn cũng có thể điều này trong phạm vi 'được cung cấp'. – zygimantus

Các vấn đề liên quan