亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于其他方法返回類型的單元測試布爾方法

基于其他方法返回類型的單元測試布爾方法

倚天杖 2023-08-09 15:26:02
單元測試新手,我正在尋找一種對布爾方法進行單元測試的方法,該方法已通過其他兩種方法結果進行驗證。 protected boolean isUpdateNeeded(){  return (method1() && method2()); }對于本示例,其他方法如下所示。protected boolean method1() {  return false; }protected boolean method2() {  return true; } 但是如果需要的話,這兩種方法可以被覆蓋。我不知道現在這是否真的重要所以我的測試背后的想法是這樣的。找到一種方法將 true/false 傳遞給 method1 或 method2 以滿足所需的可能結果。@Test public void testCheckToSeeIfUpdateIsNeeded(){    assertTrue('how to check here');    asserFalse('how to check here');   assertIsNull('was null passed?');   }
查看完整描述

2 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

如果另一個類擴展了該類并重寫了 method1 和 method2,則開發該類的人員有責任測試更改。


您可以模擬 method1 和 method2,但隨后會將類的結構與測試用例耦合起來,從而使以后更難進行更改。


你在這里有責任測試你班級的行為。我看到有問題的方法被稱為isUpdateNeeded. 那么讓我們測試一下。我將按照我的想象填寫課程。


class Updater {

    Updater(String shouldUpdate, String reallyShouldUpdate) {...}

    boolean method1() { return shouldUpdate.equals("yes"); }

    boolean method2() { return reallyShouldUpdate.equals("yes!"); }

    boolean isUpdateNeeded() { ...}

}


class UpdaterTest {

    @Test

    void testUpdateIsNeededIfShouldUpdateAndReallyShouldUpdate() {

        String shouldUpdate = "yes";

        String reallyShouldUpdate = "yes!"

        assertTrue(new Updater(shouldUpdate, reallyShouldUpdate).isUpdateNeeded());

    }

    .... more test cases .....

}

請注意此測試如何在給定輸入的情況下斷言更新程序的行為,而不是它與某些其他方法的存在的關系。


如果您希望測試演示重寫方法時會發生什么,請在測試中子類化 Updater 并進行適當的更改。


查看完整回答
反對 回復 2023-08-09
?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

所以,例如你有課:


public class BooleanBusiness {


  public boolean mainMethod(){

    return (firstBoolean() && secondBoolean());

  }


  public boolean firstBoolean(){

    return true;

  }


  public boolean secondBoolean() {

    return false;

  }


}

然后你可以編寫這樣的測試:


import static org.junit.Assert.*;

import static org.mockito.Mockito.when;


import org.junit.Test;

import org.mockito.Mockito;


public class BooleanBusinessTest {


  @Test

  public void testFirstOption() {

    BooleanBusiness booleanBusiness = Mockito.spy(BooleanBusiness.class);

    when(booleanBusiness.firstBoolean()).thenReturn(true);

    when(booleanBusiness.secondBoolean()).thenReturn(true);

    assertTrue(booleanBusiness.mainMethod());

  }


  @Test

  public void testSecondOption() {

    BooleanBusiness booleanBusiness = Mockito.spy(BooleanBusiness.class);

    when(booleanBusiness.firstBoolean()).thenReturn(true);

    when(booleanBusiness.secondBoolean()).thenReturn(false);

    assertFalse(booleanBusiness.mainMethod());

  }

}


查看完整回答
反對 回復 2023-08-09
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號