ההערות SpringJUnitConfig ו- SpringJUnitWebConfig באביב 5

1. הקדמה

במאמר מהיר זה, נסתכל על החדש @ SpringJUnitConfig ו @ SpringJUnitWebConfig ביאורים זמינים באביב 5.

ביאורים אלה הם הרכב של ביאורים JUnit 5 ו- Spring 5 ההופכים את יצירת המבחנים לקלה ומהירה יותר.

2. @ SpringJUnitConfig

@ SpringJUnitConfig משלב את שתי ההערות הבאות:

  • @ExtendWith (SpringExtension.class) מ- JUnit 5 להריץ את המבחן עם SpringExtension כיתה ו
  • @ContextConfiguration מבדיקת אביב לטעינת הקשר האביב

בואו ליצור מבחן ונשתמש בהערה זו בפועל:

@SpringJUnitConfig (SpringJUnitConfigIntegrationTest.Config.class) מחלקה ציבורית SpringJUnitConfigIntegrationTest {@Configuration class static Config {}}

שימו לב שבניגוד ל @ContextConfiguration, מחלקות תצורה מוכרזות באמצעות ערך תְכוּנָה. עם זאת, יש לציין מיקומי משאבים באמצעות ה- מיקומים תְכוּנָה.

כעת אנו יכולים לאמת שהקשר האביב באמת נטען:

@Autowired פרטי ApplicationContext applicationContext; @Test בטל שניתןAppContext_WhenInjected_ThenItShouldNotBeNull () {assertNotNull (applicationContext); }

לבסוף, כאן יש לנו את הקוד המקביל @SpringJUnitConfig (SpringJUnitConfigTest.Config.class):

@ExtendWith (SpringExtension.class) @ContextConfiguration (שיעורים = SpringJUnitConfigTest.Config.class)

3. @ SpringJUnitWebConfig

@ SpringJUnitWebConfigמשלב את אותן ההערות של @ SpringJUnitConfig בתוספת @WebAppConfiguration ממבחני האביב - לטעון את WebApplicationContext.

בואו נראה איך הערה זו עובדת:

@SpringJUnitWebConfig (SpringJUnitWebConfigIntegrationTest.Config.class) מחלקה ציבורית SpringJUnitWebConfigIntegrationTest {@Configuration Class static Config {}}

כמו @ SpringJUnitConfig, שיעורי התצורה הולכים ב ערך תְכוּנָה וכל המשאבים מוגדרים באמצעות מיקומים תְכוּנָה.

וגם ה ערך תכונה של @WebAppConfiguration יש לציין כעת באמצעות resourcePath תְכוּנָה. כברירת מחדל, מאפיין זה מוגדר ל "Src / main / webapp".

בואו נוודא כעת כי WebApplicationContext היה ממש טעון:

@Autowired פרטי WebApplicationContext webAppContext; @Test בטל givenWebAppContext_WhenInjected_ThenItShouldNotBeNull () {assertNotNull (webAppContext); }

שוב, כאן יש לנו את הקוד המקביל ללא שימוש @ SpringJUnitWebConfig:

@ExtendWith (SpringExtension.class) @WebAppConfiguration @ContextConfiguration (מחלקות = SpringJUnitWebConfigIntegrationTest.Config.class)

4. מסקנה

במדריך קצר זה הראינו כיצד להשתמש במוצג החדש @ SpringJUnitConfig ו @ SpringJUnitWebConfig ביאורים באביב 5.

קוד המקור המלא של הדוגמאות זמין באתר GitHub.


$config[zx-auto] not found$config[zx-overlay] not found