SSM JUnit4對Mybtis進行單元測試

1 Introduction

只是記錄一下自己遇到的特殊問題…正常啓動項目是沒有問題的,說明肯定是Junit的打開方式不正確

2 Junit的配置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:spring-context*.xml"})
public class BaseTest {

    @Autowired
    private UserDao userDao;
    @Autowired
    private SystemService systemService;

    @Before
    public void before() {

    }

    @After
    public void after() {

    }

    @Test
    public void test() {
        userDao.get("123");
        systemService.getUser("1");
    }

}

3 解決辦法

其實問題很簡單,就是ContextConfiguration填寫的配置文件不正確。
本來以爲只是Mybatis的接口注入有問題,但測試了一下如果帶上了Mybatis的測試文件對SystemService進入注入測試

@Autowired
private UserDao userDao;
@Autowired
private RoleDao roleDao;
@Autowired
private MenuDao menuDao;
@Autowired
private JedisSessionDAO sessionDao;

錯誤提示是說在JedisSessionDao無法注入…那我就理解是Spring環境本身加載的問題

  1. 要帶上Mybatis的配置文件
  2. 不能使用通配符的方式
  3. 概括言之便是你要把所有需要的配置文件都寫進去

Web.xml裏面這樣子寫是沒有問題的

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:/spring-context*.xml</param-value>
</context-param>

下面是正確的寫法

@ContextConfiguration({"classpath:spring-context.xml", "classpath:mybatis-config.xml", "classpath:spring-context-shiro.xml", "classpath:spring-context-jedis.xml"})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章