I am using Spring Configuration and Jersey Configuration.
This is my spring configuration:
#Component
#Configuration
#EnableScheduling
#EnableAspectJAutoProxy
#EnableTransactionManagement
#ComponentScan(basePackages = { "my.packages" })
public class SpringConfig {
private static final String MESSAGE_SOURCE_BASE_NAME = "i18n/messages";
#Profile(Profiles.APPLICATION)
#Configuration
#PropertySource("classpath:application.properties")
static class ApplicationProperties {
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder(11);
}
#Bean
public TaskScheduler taskScheduler() {
return new ConcurrentTaskScheduler();
}
#Bean
MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE_BASE_NAME);
messageSource.setUseCodeAsDefaultMessage(true);
return messageSource;
}
}
This is my Service class and interface:
public interface DAOService {
User register(User user)
}
#Service
public class DAOServiceImpl implements DAOService {
#Override
User register(User user){
return null;
}
}
This is my jersey resource:
Inside ResourceSecurityService class I want to use #Autowire for DAOService
class, but I get null pointer exception, daoService is always null.
#Component
#Path("/security")
#Produces({ MediaType.APPLICATION_JSON })
public class ResourceDAOService {
#Autowired
private DAOService daoService ; //<--- here daoService is null;
#POST
#Path("/register")
#Consumes({ MediaType.APPLICATION_JSON })
#Transactional
public Response register(User user, #Context HttpServletRequest request,
#Context HttpServletResponse response) throws AppException {
return Response.status(Response.Status.CREATED).entity(securityService.register(user)).build();
}
I am using spring version 4.3.8.RELEASE with the next dependencies:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
It could be better if you'd provide a link to your project.
Based on information I see:
make sure you have jersey-spring4 dependency
make sure your Jersey version compatible with integration dependency
check out your project configuration
I advice you to use Spring Boot with auto configurations.
Related
This is structure of my project :
scr/main/java/com/company/configuration
scr/main/java/com/company/controller
scr/main/java/com/company/myProject
scr/main/java/com/company/exception
In configuration I have 3 classes : ProjectInitializer, ProjectConfiguration and ProjectContextListener.
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.company"})
#EnableJpaRepositories("com.company")
public class ProjectConfiguration {
}
========================================================================
public class ProjectInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ProjectConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new ProjectContextListener());
}
}
====================================================================
public class ProjectContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
Security.addProvider(new BouncyCastleProvider());
Security.addProvider(new FlexiCoreProvider());
Security.addProvider(new FlexiECProvider());
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("Shutting down!");
}
}
======================================================================
I want to make connection to oracle database in myproject package. it consists some classes, the problem is with ModelAccess class:
#Service
public class ModelAccess {
#Autowired
ProjectRepository jpaRepository;
protected JpaRepository<ProjectEnt, Long> getJpaRepository() {
return jpaRepository;
}
}
============================================================================
#Transactional
public interface ProjectRepository extends
JpaRepository<ProfileEnt, Long>,IProjectRepository{
}
============================================================================
#Repository
public interface IProjectRepository extends IGenericRepository<ProfileEnt> {
}
=================================================================
This is stack trace when I deploy my project in tomcat:
Error creating bean with name 'ModelAccess':
Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field:
com.company.myproject.impl.ProjectRepository com.company.myProject.impl.ModelAccess.jpaRepository;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.company.myproject.impl.ProjectRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
============================================================================
This is part of my pom file:
<properties>
<springframework.version>4.2.0.RELEASE</springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.11.RELEASE</version>
<!--<version>2.0.8.RELEASE</version>-->
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.3</version>
</dependency>
<dependency>
<groupId>commons-discovery</groupId>
<artifactId>commons-discovery</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
The problem that IProjectRepository is not a JpaRepository. And moreover, looks like you don't need it. To fix it just remove IProjectRepository and use ProjectRepository instead.
Have a class in the package com.conf
#Configuration
public class WebConfTest {
#Autowired
private Environment environment;
}
and unit test into com.service
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { WebConfTest.class })
public class DMSServiceImplTest {
#Autowired
WebConfTest webConfTest;
#Test
public void testConnect() throws Exception {
}
}
test dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
In the IDEA navigation between beans work. But WebConfTest== null if I run test.
What is wrong?
Thanks.
#RunWith is for junit runner.
If you want to run tests with TestNG, you need to extends AbstractTestNGSpringContextTests.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-support-classes-testng
This is my first WebApp builded using Spring and i'm going mad because when i call my RestController everytime gives me 404. I tried to use the Class/Annotaion configuration instead of the XML configuration and i think that is here that the problem lives.
Here are my config classes, pom and controller.
Sorry for the huge amount of code.
For the api call i use localhost:8080/Polito/metric
Initailizer
package com.poli.config;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Order(1)
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class, SecurityConfig.class };
}
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebAppConfig.class };
}
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
RootConfig
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.poli")
#ComponentScan("com.poli")
#PropertySource("classpath:application.properties")
public class RootConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
private static final String PROPERTY_NAME_HIBERNATE_DDL_AUTO = "hibernate.hbm2ddl.auto";
private static final String PROPERTY_NAME_HIBERNATE_EJB_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties jpaProperties = new Properties();
jpaProperties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_DDL_AUTO,
env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DDL_AUTO));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_EJB_NAMING_STRATEGY,
env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_EJB_NAMING_STRATEGY));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,
env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
jpaProperties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL,
env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Autowired
private UserDetailsService customUserDetailsService;
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.userDetailsService(customUserDetailsService)
.authorizeRequests()
.antMatchers("/personal/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/index.html")
.failureUrl("/error-login.html")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/index.html");
}
}
WebAppConfig
#Configuration
#EnableWebMvc
#ComponentScan("com.poli")
public class WebAppConfig {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
SecurityInitializer
#Order(2)
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
MetricRESTController
#RestController()
#RequestMapping("/metric")
public class MetricRESTController {
#Autowired
private MetricService metricService;
#RequestMapping(method = RequestMethod.POST, value="/")
#ResponseStatus(value=HttpStatus.CREATED)
public void post(#RequestBody Metric metric){
metricService.addMetric(metric);
}
#RequestMapping(method = RequestMethod.GET, value = "/{uuid}")
public List<Metric> get(#PathVariable("uuid") String uuid){
return metricService.findByUuid(uuid);
}
#RequestMapping(method = RequestMethod.GET, value = "/")
public List<Metric> get(){
return metricService.findAllMetrics();
}
}
And finally pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Polito</groupId>
<artifactId>Polito</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<finalName>Polito</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.2.1.RELEASE</spring.version>
<spring.security.version>4.0.2.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
<mysql.connector.version>5.1.30</mysql.connector.version>
<logback.version>1.1.2</logback.version>
<slf4j.version>1.7.6</slf4j.version>
<hibernate.version>4.2.11.Final</hibernate.version>
<dbcp.version>1.4</dbcp.version>
<servletapi.version>2.5</servletapi.version>
</properties>
<dependencies>
<!-- database pool -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>${dbcp.version}</version>
</dependency>
<!-- Hibernate ORM -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring + aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- ORM integration, e.g Hibernate -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- Spring Security JSP Taglib -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- MySql Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servletapi.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
I have a web application running in Wildfly which is using Spring and JPA. Now I am moving the login module of the application as a custom module in JBoss.
Code snippet is as below.
MyLoginModule
public class MyLoginModule extends AbstractServerLoginModule
{
private Principal caller;
private char[] credential;
private String[] roleList;
#Inject
#DaoQualifier
private Dao dao;
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options) {
super.initialize(subject, callbackHandler, sharedState, options);
super.principalClassName = "com.myapp.login.LoginPrincipal";
}
#Override
public boolean login() throws LoginException
{
logger.info("inside login "+dao);
if (super.login())
{
................
}
else
{
............
}
}
}
DaoImpl class as given below.
public class DaoImpl implements Dao {
#Inject
private EntityManager em;
//implementation methods
}
Pom.xml dependencies
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.picketbox</groupId>
<artifactId>picketbox</artifactId>
<version>4.0.21.Beta1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.4.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
beans.xml
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
When this jar is deployed in JBoss/modules and server started, the dao object is always coming as null. Is there something missing in my code?
as hwellmann said, login modules aren't managed beans. He is right about the manual lookup also. I'd like just to add a example code for the lookup:
public class CustomLoginModule extends AbstractServerLoginModule {
#Inject
AuthService authService;
#Override
public boolean login() throws LoginException {
if (authService == null) {
CdiHelper.programmaticInjection(CustomLoginModule.class, this);
}
authService.authenticate();
}...
The helper:
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionTarget;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class CdiHelper {
// Nicked from: http://docs.jboss.org/weld/reference/1.1.0.Final/en-US/html_single/#d0e5286
public static <T> void programmaticInjection(Class clazz, T injectionObject) throws NamingException {
InitialContext initialContext = new InitialContext();
Object lookup = initialContext.lookup("java:comp/BeanManager");
BeanManager beanManager = (BeanManager) lookup;
AnnotatedType annotatedType = beanManager.createAnnotatedType(clazz);
InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType);
CreationalContext creationalContext = beanManager.createCreationalContext(null);
injectionTarget.inject(injectionObject, creationalContext);
creationalContext.release();
}
}
I've quoted this form https://developer.jboss.org/thread/196807 just in case the original post disappears.
Login modules aren't managed beans, so injection does not work. You have to look up your dependencies manually from JNDI or other suitable registries.
By the way, the built-in solution for dependency injection in Java EE 7 is CDI, so what's the point in using Spring?
Hy guys,
I am trying to make a test using mockito on a web application that uses spring mvc.
When it executes this line "Mockito.reset(notificacaoRepositoryMock);" it throws "org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class com.sun.proxy.$Proxy40"
I saw that in am example and it worked, I can't find what I am doing wrong here.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {TestContext.class, WebAppConfig.class})
#WebAppConfiguration
public class NotificacaoControllerTest {
private MockMvc mockMvc;
#Autowired
private NotificacaoRepository notificacaoRepositoryMock;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setUp() {
// *** Error here ***
Mockito.reset(notificacaoRepositoryMock);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
My TestContext is:
#Configuration
public class TestContext {
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("i18n/messages");
messageSource.setUseCodeAsDefaultMessage(true);
return messageSource;
}
#Bean
public NotificacaoRepository notificacaoRepository() {
return Mockito.mock(NotificacaoRepository.class);
}
}
The class I want mock is a CrudRepository interface
public interface NotificacaoRepository extends CrudRepository<Notificacao, Long> {
}
and, I think, the relevant part of my pom.xml is (spring versions and mockito)
<properties>
<hibernate.version>4.2.0.Final</hibernate.version>
<mysql.connector.version>5.1.21</mysql.connector.version>
<spring.version>4.1.6.RELEASE</spring.version>
<spring.data.version>1.8.0.RELEASE</spring.data.version>
</properties>
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
<scope>test</scope>
</dependency>
UPDATE
#jfcorugedo i tryed exactly what you said but I keep receiving the same error. My test context is just
#Configuration
public class TestContext {
#Bean
#Primary
public NotificacaoRepository notificacaoRepository() {
return Mockito.mock(NotificacaoRepository.class);
}
}
and my test class now is:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {WebAppConfig.class})
#WebAppConfiguration
#Import({TestContext.class})
public class NotificacaoControllerTest {
#Autowired
NotificacaoRepository notificacaoRepositoryMock;
#Before
public void setUp() {
Mockito.reset(notificacaoRepositoryMock); // Error >> org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class com.sun.proxy.$Proxy55
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
This is because Spring create a proxy around your bean.
Try to not inject mock using Spring
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {TestContext.class, WebAppConfig.class})
#WebAppConfiguration
public class NotificacaoControllerTest {
private MockMvc mockMvc;
private NotificacaoRepository notificacaoRepositoryMock;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setUp() {
notificacaoRepositoryMock = Mockito.mock(NotificacaoRepository.class);
Mockito.reset(notificacaoRepositoryMock);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
As far as I know, you are trying to replace the spring bean with a mock version.
In that case you have to annotate the method that produces your mock with the annotation #Primary, so Spring could choose the mock object by default in each autowired field (of course if it doesn't have any qualifier).
If you're trying to use a Spring context in your test that has some real beans and other mock beans, you have to follow this steps:
Create a #Configuration class in your test folder that inject a mock instance of the beans you want to mock
Import this configuration class in your test
For instance:
Configuration class that injects the mock
import static org.mockito.Mockito.mock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import xxx.xxx.xxx.NotificacaoRepository;
#Configuration
public class MockConfigurer {
#Bean
#Primary
public NotificacaoRepository registerMock() {
return mock(NotificacaoRepository.class);
}
}
Test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {WebAppConfig.class})
#WebAppConfiguration
#Import({MockConfigurer.class})
public class NotificacaoControllerTest {
//Now the instance injected here should be a mock object
#Autowired
private NotificacaoRepository notificacaoRepositoryMock;
...
}