常規(guī)步驟:
1、導(dǎo)入jar包,主要有兩個(gè),spring-test 和 junit4,主要用maven管理,直接依賴即可?梢栽谶@個(gè)網(wǎng)站上進(jìn)行查找或下載:http://mvnrepository.com/
2、編寫基類,這也不用每個(gè)測(cè)試類都要實(shí)現(xiàn)一遍,代碼如下:
/**
* 顯示基類,主要是用來(lái)加載配置文件的
* @author joy
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/spring/applicationContext-base.xml","classpath:springmvc-config.xml","classpath:sqlMapConfig.xml"})
public class BaseJunit4Test extends AbstractJUnit4SpringContextTests{
//do nothing
}
3、編寫測(cè)試類,注意繼承基類
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.wei.interfaces.UserService;
import com.wei.junit.BaseJunit4Test;
public class UserServiceImplTest extends BaseJunit4Test {
@Autowired
private UserService userService;
@Test
public void testGetUserById(){
assertEquals(userService.getUserById(1).getLoginName(), "admin");
}
}
注意點(diǎn):
1、已經(jīng)有了一個(gè)完整mvc層級(jí)架構(gòu),這樣依賴的時(shí)候不會(huì)報(bào)無(wú)法依賴注入的錯(cuò)誤;
2、要添加servlet-api,否則會(huì)報(bào)如下錯(cuò)誤: