java - Independent JUnit Tests with Springs @Autowired -
as beginner in test driven development encountered problem. test class begins follows:
@runwith(springjunit4classrunner.class) @transactional @dirtiescontext @contextconfiguration(locations = {"/web-test.xml"}) public class xxtest { @autowired xx xx; @autowired hibernatetemplate template; @test public void testsetgetxxvalue() throws exception { final map<string, yy> profilmap = new hashmap<string, yy>(2); profilmap.put("1", new yy()); profilmap.put("2", new yy()); simplecockpit.setvalues(profilmap); assertequals(profilmap, simplecockpit.getvalues()); }
as can see, first test method alters autowired xx-class. affects following test methods, relies on xx having autowired-values.
how can test getter , setter xx , make sure xx has autowired values rest of test methods?
thoughts:
- reset right values @ end of test method. bad because if getter / setter not working, not work.
- place first test method @ end of test class. bad because makes tests dependent on execution order.
- do not test getter / setter of xx. bad because getter / setter have tested every method.
thanks answers! i`m pretty sure has easy solution ... :)
edit: regarding questions whether unit testing getters/setters or not, decided because of reasons statet @ http://www.sundog.net/sunblog/posts/should-we-test-getters-and-setters/ .
if modify spring managed bean, use @dirtiescontext
annotation. annotation can put on test classes on test methods!
from @dirtiescontext java doc:
test annotation indicates {@link org.springframework.context.applicationcontext applicationcontext} associated test dirty , should closed:
- after current test, when declared @ method level
- after each test method in current test class, when declared @ class level class mode set {@link classmode#after_each_test_method after_each_test_method}
- after current test class, when declared @ class level class mode set {@link classmode#after_class after_class}
and in test driven development (to understanding): write explicite tests stuff has minimum complexity. never write explicite tests getter , setter. have test checks functionality, , when functionality needs getter , setter write getter , setter (at point in time) , works checked functionality started implicit.
especially in case: why use spring bean, why not using "normal" objects created new
. use "normal" classes long usefull tests, simple tests. use spring beans "bigger" tests well.
Comments
Post a Comment