第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何使用try-with-resources測(cè)試方法

如何使用try-with-resources測(cè)試方法

蕪湖不蕪 2021-05-06 14:17:59
如何對(duì)使用try-with-resources的方法進(jìn)行單元測(cè)試?由于它在try子句中使用new運(yùn)算符,因此無(wú)法對(duì)其進(jìn)行模擬。我不想使用PowerMock??磥?lái)唯一的方法就是創(chuàng)建集成測(cè)試?public void methodToBeTested(File file) {    try (FileInputStream fis = new FileInputStream(file)) {        //some logic I want to test which uses fis object    } catch (Exception e) {        //print stacktrace    }}
查看完整描述

1 回答

?
開(kāi)心每一天1111

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊

您可以將依賴項(xiàng)實(shí)例化移動(dòng)到工廠類中,并將其作為構(gòu)造函數(shù)參數(shù)傳遞給要測(cè)試的代碼。工廠類本身太簡(jiǎn)單而不會(huì)失敗,因此不需要進(jìn)行測(cè)試。


您是否打算做類似的事情:


try (FileInputStream fis = getCreatedFromFactory(file)) ??

– JavaIntern


幾乎...


@Singleton

public class InputStreamFactory { // too simple to fail -> no UnitTests

   public InputStream createFor(File file) throws IOException, FileNotFoundException {

       retrun new FileInputStream(file);

   }

}

class UnitUnderTest {

   private final InputStreamFactory inputStreamFactory;

   UnitUnderTest(@Inject InputStreamFactory inputStreamFactory){

      this.inputStreamFactory=inputStreamFactory;

   }


   public void methodToBeTested(File file) {

        try (FileInputStream fis = inputStreamFactory.createFor(file)) {

            //some logic I want to test which uses fis object

        } catch (Exception e) {

            //print stacktrace

        }

    }

}

class UnitUnderTestTest{

   @Rule

   public MockitoRule rule = MockitoJUnit.rule();


   @Mock

   private InputStreamFactory inputStreamFactory;


   @Mock

   private InputStream inputStream;


   private final File inputFile = new File("whatever");


    // no init here, mock for inputStream not yet created

   private UnitUnderTest unitUnderTest;

   /* I don't use @InjectMocks

      since it does not cause compile error

      if constructor misses parameter */


   @Before

   public void setup() {

       unitUnderTest = new UnitUnderTest(inputStreamFactory);

       doReturn(inputStream).when(inputStreamFactory).createFor(any(File.class);

   }


   @Test

   public void createsInputStreamFromFilePassed() {

       // arrange

       /* nothing to do */


       // act

       new UnitUnderTest(inputStreamFactory).methodToBeTested(inputFile);


       // assert

       verify(inputStreamFactory).createFor(inputFile); 

       verify(inputStream).close(); 

   }

}


查看完整回答
反對(duì) 回復(fù) 2021-05-19
  • 1 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)