Here is my Servlet. It gets a String that I've put in a ServletContext in my Listener.
@WebServlet(ADMIN_DISH_PATH)
public class AdminDishServlet extends HttpServlet {
private String uploadDir;
private DishService dishService;
@Override
public void init() throws ServletException {
dishService = ServiceManager.getInstance().getDishService();
ServletContext sc = getServletContext();
uploadDir = (String) sc.getAttribute(UPLOAD_DIR);
}
// doGet method
}
Here is the Test class
@ExtendWith(MockitoExtension.class)
public class AdminDishServletTest {
@Spy
AdminDishServlet adminDishServlet;
private static MockedStatic<ServiceManager> serviceManagerDummy;
@BeforeAll
static void setUp() {
serviceManagerDummy = Mockito.mockStatic(ServiceManager.class);
}
@AfterAll
static void close() {
serviceManagerDummy.close();
}
@Test
void whenGetReturnDishes() throws ServletException, IOException {
String uploadDir = "/testDir";
serviceManagerDummy.when(ServiceManager::getInstance).thenReturn(serviceManager);
when(serviceManager.getDishService()).thenReturn(dishService);
when(servletContext.getAttribute(UPLOAD_DIR)).thenReturn(uploadDir);
when(adminDishServlet.getServletContext()).thenReturn(servletContext); // Error happens here
adminDishServlet.init();
adminDishServlet.doGet(request, response);
// Some assertions
}
}
The exception I have
java.lang.IllegalStateException: ServletConfig has not been initialized
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:159)
Code from GenericServlet (javax package) where the exception happens
public ServletContext getServletContext() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletContext();
}
But how do I pass ServletConfig to Generic Servlet or Initialize it?
CodePudding user response:
Create a mock ServletConfig
, mock its getServletContext()
method to return your mocked ServletContext
, and use the other init
method: init(servletConfig)
. Then you don't need to mock the getServletContext()
method of your servlet.