
Java Tutorial 第五堂(3)測試與重構 DvdController
Java Tutorial 第五堂(2)JUnit 與 Gradle << 前情 在瞭解如何使用 JUnit 之後,接著來試著重新做一次 Java Tutorial 第五堂(1) 中的練習,由於時間有限,我們僅將重點放在 練習 16:為 DvdController 建立測試在 Lab 檔案的 exercises/exercise16 中有個 DVDLibrary 目錄,已經事先將練習 14 與練習 15 中一些可重用的程式碼(像是 Dvd.java、DvdDao.java、DvdLibraryService.java 等)與設定檔(像是 build.gradle 等)準備好,不過, 請在 src/test/java/tw/codedata 中建立一個 DvdControllerTest.java,如下撰寫程式碼: package tw.codedata; import static org.junit.Assert.*; import org.junit.*; import java.util.*; import org.springframework.ui.Model; public class DvdControllerTest { List<Dvd> dvds; Map attributesOfModel; DvdController controller; Model model; @Before public void setUp() { dvds = new ArrayList<>(Arrays.asList( new Dvd("dvd1", 1, 2, new Director("director1")))); attributesOfModel = new HashMap(); controller = new DvdController(); controller.setDvdDao(new DvdDao() { public void saveDvd(Dvd dvd) { dvds.add(dvd); } public List<Dvd> allDvds() { return dvds; } }); model = new Model() { @Override public Model addAttribute(String attributeName, Object attributeValue) { attributesOfModel.put(attributeName, attributeValue); return this; } @Override public Model addAttribute(Object attributeValue) { throw new UnsupportedOperationException("Not supported yet."); } 其他方法實作,可如上撰寫就好,因為用不到 ... }; } @Test public void testList() { String result = controller.list(model); assertEquals("list", result); assertEquals(dvds, attributesOfModel.get("dvds")); } @Test public void testAdd() { String result = controller.add("dvd1", 1, 2, "director1", model); Dvd dvd = (Dvd) attributesOfModel.get("dvd"); assertEquals("success", result); assertEquals(2, dvds.size()); assertEquals("dvd1", dvd.getTitle()); } } 在這邊看到
注意,無論是 舉例來說,我們用了 完成以上程式之後,執行 練習 17:重構與測試 DvdController接下來,可以重構 package tw.codedata; import static org.junit.Assert.*; import org.junit.*; import java.util.*; import org.springframework.ui.Model; public class DvdControllerTest { List<Dvd> dvds; Map attributesOfModel; DvdController controller; Model model; @Before public void setUp() { ...同前... controller = new DvdController(); controller.setDvdLibraryService(new DvdLibraryService() { @Override public List<Dvd> allDvds() { return dvds; } @Override public Dvd addDvd(String title, Integer year, Integer duration, String directorName) { Dvd dvd = new Dvd(title, year, duration, new Director(directorName)); dvds.add(dvd); return dvd; } }); ...同前... } ...同前... } 因為是對 完成以上程式之後,執行 在修改(或撰寫)程式之前,先撰寫測試,這是測試驅動(Test-driven)的概念,這樣,你就能先思考你想要的程式介面或規格。 接下來,你可以如 Java Tutorial 第五堂(1) 中的練習 14 修改 |