I'm trying to test my Spring web app but i have some problems.
I added a test class in my maven
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testName() throws Exception {
List<UserEntity> userEntities = userService.getAllUsers();
Assert.assertNotNull(userEntities);
}
}
But i got a NullPointerException on userService when i try to run this test.
IntelliJ say "Could not autowire. No beans of 'UserService' type found.
After adding @RunWith(SpringJUnit4ClassRunner.class) , i got this exception
java.lang.IllegalStateException: Neither GenericXmlContextLoader nor AnnotationConfigContextLoader was able to detect defaults, and no ApplicationContextInitializers were declared for context configuration
How can i solve it ? And i think i need to run this test on my tomcat server but how can i deploy for testing with IntelliJ ? (like command 'mvn clean install tomcat7:run-war-only')
You have to provide the location of your Spring context file to be initialized before the test starts.
Test class
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {
@Autowired
private UserService userService;
@Test
public void testName() throws Exception {
List<UserEntity> userEntities = userService.getAllUsers();
Assert.assertNotNull(userEntities);
}
}
your-spring-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="userService" class="java.package.UserServiceImpl"/>
</beans>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With