Spring下的单元测试是十分完善的,原来一直困扰的问题是:Service、Controller类使用的基础类都是Autowired,这样就不必在Context.xml中进行配置,调用者也无需写get、set方法,但问题是在进行unitTest过程中,test不能自动加载这些autowired的基础类,运行就会抛出null,
今天发现:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/thesisContext.xml")
可以解决这个问题。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/thesisContext.xml")
public class ArticleServiceTest {
@Autowired
private IArticleService articleService;
@Before
@Test
public void testSaveArType() {
ArticleType at = new ArticleType();
at.setName("气候与全球经济");
int result = this.articleService.saveArType(at);
assertEquals(2,result);
}
}
问题全解决了。
public class ArticleService implements IArticleService {
@Autowired
private IArticleDao articleDao;
@Autowired
private IArticleTypeDao articleTypeDao;
public int saveArType(ArticleType at) {
return articleTypeDao.save(at);
}