自動化轉配bean的測試案例分析
package soundsystem; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.StandardOutputStreamLog; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=CDPlayerConfig.class) public class CDPlayerTest { @Rule public final StandardOutputStreamLog log = new StandardOutputStreamLog(); @Autowired private MediaPlayer player; @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); } @Test public void play() { player.play(); assertEquals( "Playing Sgt. Pepper's Lonely Hearts Club Band" + " by The Beatles\n", log.getLog()); } }
觀察代碼可知,有兩處使用斷言:編寫代碼的時候我們總會做出一些假設,比如假設3+5的值為10,然后取驗證,發現不等於10,而等於8,而我們用代碼捕捉我們的假設稱為斷言
第一處斷言:斷言cd這個自動化裝配的bean已經裝配進來了
第二處斷言:斷言控制台輸出的結果與 "Playing Sgt. Pepper's Lonely Hearts Club Band by The Beatles\n" 相同
兩種斷言的表達式均為Boolean值
還有一個不太常見的StandardOutputStreamLog 對象,此對象是基於控制台的輸出去做斷言,不給過該方法已經不推薦使用,替代的是 org.junit.contrib.java.lang.system.SystemOutRule
同樣在自學Spring的小伙伴,如果看到我的博客,希望留下你的聯系方式,我們一起加油!!!