2021. 11. 9. 11:44ใSpring
https://hyejin.tistory.com/243?category=1022293
[Spring] DI ์ ํ๋ฆฌ์ผ์ด์ Junit ํ ์คํธ ํด๋์ค ์์ฑํ๊ธฐ
1. Junit Junit์ ๋จ์ํ ์คํธ ํ๋ ์์ํฌ์ด๋ค. Junit์ @Test ๋ฉ์๋๊ฐ ๊ฐ๊ฐ ํธ์ถ๋ ๋ ๋ง๋ค ์๋ก์ด ์ธ์คํด์ค๋ฅผ ์์ฑํ์ฌ ๋ ๋ฆฝ์ ์ธ ํ ์คํธ๊ฐ ์ด๋ฃจ์ด์ง๋๋ก ํ๋ค. โ ๋จ์ํ ์คํธ๋? ๋ชจ๋ ํจ์์ ๋ฉ์๋
hyejin.tistory.com
์ ๊ธ์ Junit ํ ์คํธ ํด๋์ค๋ฅผ ์์ฑํด์ ์คํํด๋ดค๋ค.
์ด๋ฒ์๋ ๋ ๋์๊ฐ Sprint-Test๋ฅผ ์ฌ์ฉํด DI ์ ํ๋ฆฌ์ผ์ด์ ํ ์คํธ ํด๋์ค๋ฅผ ์์ฑํ ๊ฒ์ด๋ค.
1. Sprint-test ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ค์นํ๊ธฐ
https://mvnrepository.com/artifact/org.springframework/spring-test
๊ฐ์ฅ ์ต์ ๋ฒ์ ๋ฐ์ ๋ฒ์ ์ ์ค์นํ ์์ ์ด๋ค.
2. Spring-Test annotation
1๏ธโฃ @RunWith(SpringJunit4ClassRunner.class)
@RunWith์ Junit ํ๋ ์์ํฌ์ ํ ์คํธ ์คํ๋ฐฉ๋ฒ์ ํ์ฅํ ๋ ์ฌ์ฉํ๋ค.
SpringJunit4ClassRunner๋ผ๋ ํด๋์ค๋ฅผ ์ง์ ํด์ฃผ๋ฉด Junit์ด ํ ์คํธ๋ฅผ ์งํํ๋ ์ค์ ApplicationContext๋ฅผ ๋ง๋ค๊ณ ๊ด๋ฆฌํ๋ ์์ ์ ์งํํด์ค๋ค.
@RunWith์ ๊ฐ๊ฐ์ ํ ์คํธ๋ณ๋ก ๊ฐ์ฒด๊ฐ ์์ฑ๋๋ค ํ๋๋ผ๋ ์ฑ๊ธํค์ ApplicationContext๋ฅผ ๋ณด์ฅํ๋ค.
2๏ธโฃ @ContextConfiguration
์คํ๋ง ๋น(Bean) ์ค์ ํ์ผ์ ์์น๋ฅผ ์ง์ ํ ๋ ์ฌ์ฉํ๋ ์ด๋ ธํ ์ด์ ์ด๋ค.
3๏ธโฃ @Autowired
์คํ๋งDI์์ ์ฌ์ฉํ๋ ์ด๋ ธํ ์ด์ ์ผ๋ก ํด๋น ๋ณ์์ ์๋์ผ๋ก Bean์ ๋งคํํด์ค๋ค.
์คํ๋ง ๋น ์ค์ ํ์ผ์ ์ฝ๊ธฐ ์ํด ๊ตณ์ด GenricXmlApplicationContext๋ฅผ ์ฌ์ฉํ ํ์๊ฐ ์๋ค.
3. Sprint-Test๋ฅผ ์ฌ์ฉํ ํ ์คํธ ํด๋์ค ์์ฑ
https://hyejin.tistory.com/242?category=1022293
[Spring] DI ์ ํ๋ฆฌ์ผ์ด์ ๋ง๋ค๊ธฐ
Spring DI Application ๋ง๋ค๊ธฐ 1๏ธโฃ POJO ํด๋์ค ์์ฑํ๊ธฐ => Printer๋ผ๋ ์ธํฐํ์ด์ค๋ฅผ ์์ฑํ๊ณ StringPrinter๊ฐ ์ด๋ฅผ ์ฐธ์กฐํด์ ์ฌ์ฉํ ์์ ์ด๋ค. ๊ทธ๋ฆฌ๊ณ Hello ์๋ฐ ํด๋์ค๋ StringPrinter๋ฅผ ์ง์ ์ฌ์ฉํ..
hyejin.tistory.com
์ด๋ฒ์๋ ์ ๊ธ์์ ๋ง๋ DI ์ ํ๋ฆฌ์ผ์ด์ ์ผ๋ก ํ ์คํธ ํด๋์ค๋ฅผ ์์ฑํ ๊ฒ์ด๋ค.
@Autowired ๋ฅผ ์ฌ์ฉํด์ ์๋์ผ๋ก ๋น์ ๋งคํํด์ฃผ๋๋ก ํ๋ค.
@RunWith์ ํตํด junit ํ๋ ์์ํฌ ํ ์คํธ๋ฅผ ํ์ฅํด์ฃผ๊ณ , SpringJunit4ClassRunner ํด๋์ค๋ฅผ ์ง์ ํด์ฃผ์ด jUnit ํ ์คํธ๋ฅผ ์งํํ๋ ์ค์ ApplicationContext๋ฅผ ๋ง๋ค๊ณ ๊ด๋ฆฌํ๋ ์์ ์ ์งํํ๋ค.
@ContextConfiguration์ ํตํด ์คํ๋ง ๋น ์ค์ ํ์ผ์ ๊ฒฝ๋ก๋ฅผ ์ง์ ํด์ฃผ์ด ๋ฐ์ ์ฝ๋๋ก ๋ฐ๋ก ์์ฑํด์ฃผ์ง ์์๋ ๋๋ค.
4. ์คํ๊ฒฐ๊ณผ