Skip to content

Commit 0b85b0a

Browse files
lor6pivovarit
authored andcommitted
functional bean registration test (eugenp#2503)
1 parent 25263f1 commit 0b85b0a

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.functional;
2+
3+
import java.util.Random;
4+
5+
import org.springframework.stereotype.Component;
6+
7+
public class MyService {
8+
9+
public int getRandomNumber(){
10+
return (new Random().nextInt(10));
11+
}
12+
13+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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

Comments
 (0)