最近和同事讨论过几次如何写单元测试之后,突然意识到,是要写点什么了。
什么是单元测试, 维基百科上是这么定义的:
unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine if they are fit for use.[1] Intuitively, one can view a unit as the smallest testable part of an application.
简而言之,就是验证系统中最小可测试单元的功能是否正确的自动化测试。因此,单元测试的目地就是“对被测试对象的职责进行验证”, 在写单元测试之前,先识别出被测试对象的职责,就知道该怎么写这个单元测试了。
//load_spec.jsit("should show error message when ajax request failed",function(){spyOn($,"ajax").andCallFake(function(params){params.beforeSend();params.complete();params.error("","404");});vartrigger=$(".itemContainer .trigger");trigger.click();expect($(".itemContainer .error").length).toBe(1);expect($(".ajax-loading").length).toBe(0);});
#创建评论application.comments.create{:text=>"this is a nice app"}movie.comments.create{:text=>"this is a nice movie"}game.comments.create{:text=>"this is a nice game"}#查看评论application.commentsmovie.commentsgame.comments
classCommentbelongs_to:commentable,:polymorphic=>trueendclassApplicationhas_many:comments,:as=>:commentableendclassMoviehas_many:comments,:as=>:commentableendclassGamehas_many:comments,:as=>:commentableend#添加评论movie.comments.create{:text=>'this is realy nice'}#查看评论movie.coments