|
| 1 | +package com.baeldung.functional; |
| 2 | + |
| 3 | +import static org.junit.Assert.*; |
| 4 | + |
| 5 | +import org.junit.Test; |
| 6 | +import org.junit.runner.RunWith; |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; |
| 8 | +import org.springframework.boot.test.context.SpringBootTest; |
| 9 | +import org.springframework.test.context.junit4.SpringRunner; |
| 10 | +import org.springframework.web.context.support.GenericWebApplicationContext; |
| 11 | + |
| 12 | +import com.baeldung.Spring5Application; |
| 13 | + |
| 14 | +@RunWith(SpringRunner.class) |
| 15 | +@SpringBootTest(classes = Spring5Application.class) |
| 16 | +public class BeanRegistrationTest { |
| 17 | + |
| 18 | + @Autowired |
| 19 | + private GenericWebApplicationContext context; |
| 20 | + |
| 21 | + @Test |
| 22 | + public void whenRegisterBean_thenOk() { |
| 23 | + context.registerBean(MyService.class, () -> new MyService()); |
| 24 | + MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService"); |
| 25 | + assertTrue(myService.getRandomNumber() < 10); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + public void whenRegisterBeanWithName_thenOk() { |
| 30 | + context.registerBean("mySecondService", MyService.class, () -> new MyService()); |
| 31 | + MyService mySecondService = (MyService) context.getBean("mySecondService"); |
| 32 | + assertTrue(mySecondService.getRandomNumber() < 10); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + public void whenRegisterBeanWithCallback_thenOk() { |
| 37 | + context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false)); |
| 38 | + MyService myCallbackService = (MyService) context.getBean("myCallbackService"); |
| 39 | + assertTrue(myCallbackService.getRandomNumber() < 10); |
| 40 | + } |
| 41 | + |
| 42 | +} |
0 commit comments