functional bean registration test (#2503)
This commit is contained in:
parent
25263f1d6f
commit
0b85b0a466
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.functional;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
public class MyService {
|
||||||
|
|
||||||
|
public int getRandomNumber(){
|
||||||
|
return (new Random().nextInt(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.functional;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
|
import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||||
|
|
||||||
|
import com.baeldung.Spring5Application;
|
||||||
|
|
||||||
|
@RunWith(SpringRunner.class)
|
||||||
|
@SpringBootTest(classes = Spring5Application.class)
|
||||||
|
public class BeanRegistrationTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private GenericWebApplicationContext context;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRegisterBean_thenOk() {
|
||||||
|
context.registerBean(MyService.class, () -> new MyService());
|
||||||
|
MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService");
|
||||||
|
assertTrue(myService.getRandomNumber() < 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRegisterBeanWithName_thenOk() {
|
||||||
|
context.registerBean("mySecondService", MyService.class, () -> new MyService());
|
||||||
|
MyService mySecondService = (MyService) context.getBean("mySecondService");
|
||||||
|
assertTrue(mySecondService.getRandomNumber() < 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRegisterBeanWithCallback_thenOk() {
|
||||||
|
context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false));
|
||||||
|
MyService myCallbackService = (MyService) context.getBean("myCallbackService");
|
||||||
|
assertTrue(myCallbackService.getRandomNumber() < 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue