簡體   English   中英

為具有組合的類編寫測試的最佳實踐是什么

[英]What is the best practice for writing tests for classes with composition

假設我有類Formater

class Formatter {
  public FormattedData format(Map<String, Data> data) {
    return .....
  }  
}

和另一個使用Formatter並可以返回格式化數據的類Collector

class Collector {
  Formatter formatter;
  Map<Id, Data> map = new HashMap<>()

  class Collector (Formatter formatter) {
    this.formatter = formatter;  
  }

  public void addData(Data data) (
    map.put(data.getId(), data);
  }

  public FormattedData getFormattedData() {
    return formatter.format(map)
  }

所以問題 - 我想寫測試。 我為Formatter類編寫了所有測試,但是我應該如何測試Collector

因為我不應該依賴收集器的實現 - 我需要復制Formatter所有測試並將它們作為Collector輸入傳遞。 當然,在測試中我會將Map<String, Data> data更改為Data data作為輸入數據類型,但無論如何都會有大量代碼重復。 我怎樣才能避免它?

您使用模擬,因此您不依賴於格式化程序的實現。

@Test
@ExtendWith(MockitoExtension.class) // @RunWith(MockitoJUnitRunner.class) for JUnit 4
class CollectorTest {
    @InjectMocks
    private Collector sut;

    @Mock
    private Formatter formatter;

    public FormattedData getFormattedData() {
        FormattedData formatted = mock(FormattedData.class);
        when(formatter.format(any()).thenReturn(formatted);

        FormattedData result = sut.getFormattedData();

        // verify injected formatter was called
        verify(formatter).format(any());
        // verify the result of the formatter is returned by the collector
        assertThat(result).isSameAs(formatted);
    }
}

暫無
暫無

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

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