【问题标题】:What is the best practice for writing tests for classes with composition为具有作文的课程编写测试的最佳实践是什么
【发布时间】:2020-02-06 20:57:34
【问题描述】:

假设我有课程Formater

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

另一个类Collector使用Formatter并可以返回格式化数据

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&lt;String, Data&gt; data 更改为Data data 作为输入数据类型,但无论如何都会有大量的代码重复。我怎样才能避免它?

【问题讨论】:

  • 嘲讽就是答案。您将模拟的Formatter 传递给构造函数,然后检查是否调用了Formatter 上的适当方法。实际上,我不完全确定您是否真的需要对几乎什么都不做的类进行测试(真的没有逻辑)。
  • 用 Mockito 模拟。

标签: java testing


【解决方案1】:

您使用模拟,因此您不依赖于格式化程序实现。

@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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多