SpringMVC + Junit搭建

SpringMVC入门有个很好的教程:使用IntelliJ IDEA开发SpringMVC网站

然后我想加入Junit测试下,结果一直报错:

  1. 要么UserRepository找不到
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UserRepositoryTest': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.grapetec.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

  2. 要么mvc-dispatcher-servlet.xml文件找不到。
    java.lang.IllegalStateException: Failed to load ApplicationContext

主要问题:

  1. ContextConfiguration配成了classpath*
  2. working directory没有配置正确

解决方案:

  1. ContextConfiguration( locations = {"file:mvc-dispatcher-servlet.xml"} )
    这里的配置要正确。
  2. 配置单元测试路径如下(之前这里是MODULE_WORKING_DIR,这个变量应该是新版IntelliJ引入的变量,直接改成如下路径):


    SpingMVC_Junit.png

单元测试代码如下:

import com.grapetec.model.UserEntity;
import com.grapetec.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;


@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration( locations = {"file:mvc-dispatcher-servlet.xml"} )
public class UserRepositoryTest {

    @Autowired
    UserRepository userRepository;

    @Test
    public void testFirst( ){
        int id = 1;
        UserEntity userEntity = userRepository.findById( id ).get();
        System.out.println( "ID:" + id + " NickName:" + userEntity.getNickname() );
    }
}

后续:

  1. 这种解决方案非常粗糙,还是期待有大神提供比较细腻的解决方案。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。