弹簧测试和maven

alv*_*oun 3 java junit spring intellij-idea maven

我正在尝试测试我的Spring网络应用程序,但我遇到了一些问题.

我在我的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是NullPointerException当我尝试运行此测试时,我得到了一个用户服务.IntelliJ说"无法自动装配.没有找到'UserService'类型的bean.添加后@RunWith(SpringJUnit4ClassRunner.class),我得到了这个例外

java.lang.IllegalStateException: Neither GenericXmlContextLoader nor AnnotationConfigContextLoader was able to detect defaults, and no ApplicationContextInitializers were declared for context configuration
Run Code Online (Sandbox Code Playgroud)

我怎么解决呢?我想我需要在我的tomcat服务器上运行这个测试但是我如何使用IntelliJ进行测试?(比如命令'mvn clean install tomcat7:run-war-only')

Xst*_*ian 5

您必须在测试开始之前提供要初始化的Spring上下文文件的位置.

考试班

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您-弹簧的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>
Run Code Online (Sandbox Code Playgroud)