|
| 1 | +package com.baeldung.typesofbeaninjection; |
| 2 | + |
| 3 | +import com.baeldung.typesofbeaninjection.domain.Car; |
| 4 | +import com.baeldung.typesofbeaninjection.domain.Engine; |
| 5 | +import org.junit.Test; |
| 6 | +import org.springframework.context.ApplicationContext; |
| 7 | +import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
| 8 | +import org.springframework.context.support.ClassPathXmlApplicationContext; |
| 9 | + |
| 10 | +import static org.junit.Assert.assertEquals; |
| 11 | +import static org.junit.Assert.assertNotNull; |
| 12 | + |
| 13 | +public class TypeOfBeanInjectionUnitTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + public void whenConstructionInjectionInXML_thenCarHasEngine() { |
| 17 | + ApplicationContext applicationContext |
| 18 | + = new ClassPathXmlApplicationContext("/typesofbeaninjection-context.xml"); |
| 19 | + Car car = applicationContext.getBean("alices-car", Car.class); |
| 20 | + |
| 21 | + checkEngine(car.getEngine()); |
| 22 | + } |
| 23 | + |
| 24 | + @Test |
| 25 | + public void whenPropertyInjectionInXML_thenCarHasEngine() { |
| 26 | + ApplicationContext applicationContext |
| 27 | + = new ClassPathXmlApplicationContext("/typesofbeaninjection-context.xml"); |
| 28 | + Car car = applicationContext.getBean("bobs-car", Car.class); |
| 29 | + |
| 30 | + checkEngine(car.getEngine()); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void whenConstructionInjectionAnnotations_thenCarHasEngine() { |
| 35 | + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); |
| 36 | + com.baeldung.typesofbeaninjection.domain.autowired.constructor.Car car |
| 37 | + = applicationContext.getBean(com.baeldung.typesofbeaninjection.domain.autowired.constructor.Car.class); |
| 38 | + |
| 39 | + checkEngine(car.getEngine()); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void whenPropertyInjectionAnnotations_thenCarHasEngine() { |
| 44 | + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); |
| 45 | + com.baeldung.typesofbeaninjection.domain.autowired.properties.Car car |
| 46 | + = applicationContext.getBean(com.baeldung.typesofbeaninjection.domain.autowired.properties.Car.class); |
| 47 | + |
| 48 | + checkEngine(car.getEngine()); |
| 49 | + } |
| 50 | + |
| 51 | + private void checkEngine(Engine engine) { |
| 52 | + assertNotNull(engine); |
| 53 | + assertEquals("V8", engine.getType()); |
| 54 | + assertEquals(5, engine.getVolume()); |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | +} |
0 commit comments