Spring入門(四)Spring-test模塊


自動化轉配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的小伙伴,如果看到我的博客,希望留下你的聯系方式,我們一起加油!!!

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM