[英]How to use JUnit4 to test a void method?
所以我的代碼看起來如此(我知道我沒有編寫減法規則但忽略了它):必須聲明該方法(它是一個賦值)並且我還實現了一個接口
public class RomanNumber implements Number {
public String roman;
public RomanNumber(String roman) {
this.roman = roman;
}
public void fromIntValue(int value) {
String roman ="";
if (value < 0) {
roman = " ";
}
while (value >= 1000) {
roman += "M";
value -= 1000;
}
while (value >= 500) {
roman += "D";
value -= 500;
}
while (value >= 100) {
roman += "C";
value -= 100;
}
while (value >= 50) {
roman += "L";
value -= 50;
}
while (value >= 10) {
roman += "X";
value -= 10;
}
while (value >= 5) {
roman += "V";
value -= 5;
}
while (value >= 1) {
roman += "I";
value -= 1;
}
this.roman=roman;
}
我的 JUnit 測試:
public void fromIntValue() {
RomanNumber rom = new RomanNumber("MMMCCLV");
rom.fromIntValue(3255);
Assert.assertEquals({"MMCCLV"},rom.fromIntValue(3255));
}
還有我的錯誤信息:
Error:(26, 54) java: 'void' type not allowed here
Unittest 驗證公共可觀察行為,即返回值(如果有)或與依賴項的通信。
您的代碼應該更改對象的內部狀態。
訪問內部狀態(存儲翻譯數字的變量)將違反封裝/信息隱藏,這是面向對象編程最重要的原則之一。
畢竟,對象狀態的變化應該導致對象公共可觀察行為的變化。 在您的情況下,應該有一個getter方法來公開內部存儲的羅馬數字。 所以你的測試應該使用這個getter來檢索狀態。
您將結果保存在名為roman
的私有變量上,但之后不會在任何地方讀取它。
fromIntValue
方法僅用於觸發轉換而不返回最終結果( void
return)。 這就是您收到錯誤的原因。
您需要創建一些方法來獲取RomanNumber
類上的羅馬值,例如getRoman
方法:
public String getRoman() {
return this.roman;
}
因此,您的測試可以讀取結果:
RomanNumber rom = new RomanNumber("MMMCCLV");
rom.fromIntValue(3255);
Assert.assertEquals("MMCCLV", rom.getRoman());
您將結果保存到私人成員中。 為此,您需要使用 getter 方法或 PowerMock 包的 WhiteBox 類來獲取該成員。
public String getRoman() {
return this.roman;
}
String roman = WhiteBox(rom,"roman");// 返回羅馬成員的值 Assert.assertEquals("MMCCLV", roman);
String roman = WhiteBox(rom,"roman");// return the value of roman member
Assert.assertEquals("MMCCLV", roman);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.