簡體   English   中英

具有 boolean 條件和 JUnit 的測試無效方法

[英]Test void method that has boolean conditions with JUnit

我正在嘗試使用 Junit 測試內部具有 boolean 條件的 void 方法

/** Method to create request */
public void createRequest(String name) {

  if (verifyName(name)) {
    testRepo.getRequest(name); // Void method from test repo
    demoRepo.testMethod(name); // Another void method from demo repo
  }
}

/** Validate name */
private boolean verifyName(String name) {

 return "Test".equals(name);
}

在這種情況下,當 verifyName() 使用 JUnit 返回true/false時,測試 void 方法的最佳方法是什么?

預期的測試場景:

  1. verifyName() 返回true --> 斷言或確保方法被執行。
  2. verifyName() return false --> assert 或確保方法不會被執行。

您可以根據條件驗證是否調用了某些 function

嘗試類似的東西

@Test
public void testValidName() {
    service.createRequest("Test");
    verify(testRepo, times(1)).getRequest();
    verify(demoRepo, times(1)). testMethod();
}

您可以簡單地編寫兩個場景:

@Captor
private String ArgumentCaptor<String> nameCaptor;

@Test
public void testForValidName() {
    service.createRequest("Test");
    Mockito.verify(testRepo, Mockito.times(1)).getRequest(nameCaptor.capture());
    Mockito.verify(demoRepo, Mockito.times(1)).testMethod(nameCaptor.capture());
    List<String> capturedValues = nameCaptor.getValues();
    Assert.assertEquals("Test", capturedValues.get(0));
    Assert.assertEquals("Test", capturedValues.get(1));
}

@Test
public void testForInValidName() {
   service.createRequest("Test1");
   Mockito.verifyNoMoreInteractions(testRepo);
   Mockito.verifyNoMoreInteractions(demoRepo);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM