lundi 27 novembre 2017

Spring Testing Context Autowired

Sorry for the silly question, but i can't find out why this code is not working with Spring.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DBDumpTest {
    @Autowired
    private DataSource source;

    @Configuration
    static class ContextConfiguration {
        @Bean
        public DataSource dataSource() {
            return Mockito.mock(DataSource.class);
        }
    }

    @Test
    public void testDump() throws Exception {
        Assert.assertNotNull(source); //OK
        Assert.assertNotNull(new DBDump().getDatasource()); //NULL NOT OK
    }
}

With Class:

public class DBDump {
    private static final Logger logger = LoggerFactory.getLogger(DBDump.class);

    @Autowired
    private DataSource datasource;


    public DataSource getDatasource() {
        return datasource;
    }
}

So why does new DBDump().getDatasource() not return the Mocked Instance, while in the Test-Class the @Autowired Annotation seems to work?

Aucun commentaire:

Enregistrer un commentaire