I have a servlet that makes use AnnotationConfigApplicationContext
, I want to test this class. How do i mock AnnotationConfigApplicationContext
or is there way to test below class. I dont want to use spring-auto-mock due to very specifics reasons.
Below is the code
@WebServlet("/Application")
public class Application extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String birthPlace = request.getParameter("birthPlace");
PersonData person = new PersonData();
person.setBirthPlace(birthPlace);
person.setName(name);
PersonDao dao = context.getBean(PersonDao.class);
dao.insertPerson(person);
}
}
@Configuration
@ComponentScan(basePackages = { "com.test.*" })
public class JavaConfig {
@Bean
public NamedParameterJdbcOperations getLettuceConnectionFactory() {
return new NamedParameterJdbcTemplate(mysqlDataSource());
}
public DataSource mysqlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
dataSource.setUsername("guest_user");
dataSource.setPassword("guest_password");
return dataSource;
}
}
Below is the code that i have written so far
public class ApplicationTest {
@Mock
AnnotationConfigApplicationContext context;
@Test
public void testApplication() throws Exception{
Application app = new Application();
PowerMockito.whenNew(AnnotationConfigApplicationContext.class).withAnyArguments().thenReturn(context);
app.process();
}
}
I see that all beans in JavaConfig
are trying get generated , since I will not be able to access database from Junit the bean creation failes, but I dont want bean to be created in first place.
Am I initiating mock for AnnotationConfigApplicationContext
correctly?
is the issue due to AnnotationConfigApplicationContext
private
static
field?
How do i handle this scenario.
Can junit testing for above class be achieved without Power Mockito if i remove static
final
field?