[英]What is the best practice for writing tests for classes with composition
Assume I have class Formater
假设我有类Formater
class Formatter {
public FormattedData format(Map<String, Data> data) {
return .....
}
}
and another class Collector
that uses Formatter
and can return formatted data和另一个使用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)
}
So the problem - I want to write tests.所以问题 - 我想写测试。 I wrote all the tests for Formatter
class, but how should I test Collector
?我为Formatter
类编写了所有测试,但是我应该如何测试Collector
?
Since I should not rely on implementation of collector - I need to copy all tests for Formatter
and pass them as input for Collector
.因为我不应该依赖收集器的实现 - 我需要复制Formatter
所有测试并将它们作为Collector
输入传递。 Surely in tests I would change Map<String, Data> data
to Data data
as input data type, but anyway there will be a huge code duplication.当然,在测试中我会将Map<String, Data> data
更改为Data data
作为输入数据类型,但无论如何都会有大量代码重复。 How can I avoid it?我怎样才能避免它?
You use mocks so you don't depend on the formatter implementation.您使用模拟,因此您不依赖于格式化程序的实现。
@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.