SpringMVC入门有个很好的教程:使用IntelliJ IDEA开发SpringMVC网站
然后我想加入Junit测试下,结果一直报错:
-
要么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)} -
要么mvc-dispatcher-servlet.xml文件找不到。
java.lang.IllegalStateException: Failed to load ApplicationContext
主要问题:
- ContextConfiguration配成了classpath*
- working directory没有配置正确
解决方案:
- ContextConfiguration( locations = {"file:mvc-dispatcher-servlet.xml"} )
这里的配置要正确。 -
配置单元测试路径如下(之前这里是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() );
}
}
后续:
- 这种解决方案非常粗糙,还是期待有大神提供比较细腻的解决方案。
网友评论