junit - Testing spring bean with post construct -
i have bean similar this:
@service public class { @autowired private b b; @postconstruct public void setup() { b.call(param); } } @runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = { application.class, config.class }) @webintegrationtest(randomport = true) public class test { @autowired b b; @before public void setup() throws exception { when(b.call(any())).thenreturn("smth"); } @test public void test() throws exception { // test... } } the problem postconstruct called before setup when test run.
if want write unit test of a, don't use spring. instead, instantiate a , pass stub/mock of b (either using constructor injection or reflectiontestutils set private field).
for example:
@service public class { private final b b; @autowired public a(b b) { this.b = b; } @postconstruct public void setup() { b.call(param); } } -
public class test { @test public void test() throws exception { b b = mock(b); a = new a(b); // write tests } } if have use spring, because want write integration test, use different application context, replace b stub/mock.
for example, assuming b instantiated in production class this:
@configuration public class production { @bean public b b() { return new b(); } } write @configuration class tests:
@configuration public class tests { @bean public b b() { // using mockito example b b = mockito.mock(b.class); mockito.when(b).thenreturn("smth"); return b; } } reference in test @springapplicationconfiguration annotation:
@springapplicationconfiguration(classes = { application.class, tests.class })
Comments
Post a Comment