如何在单元测试时避免创建多余的字符串?
例如字符串“SERIALIZED”似乎有点不必要和任意......你会用什么代替?
Object update=new Object();
FileWriter writer=mock(FileWriter.class);
Serializer serializer=mock(Serializer.class);
when(cache.getWriter(update)).thenReturn(writer);
when(serializer.serialize(update)).thenReturn("SERIALIZED");
FileRecorder recorder=new FileRecorder(serializer);
recorder.receive(update);
verify(writer).write("SERIALIZED");
答案 0 :(得分:4)
我不会调用您用来验证测试是否通过多余的字符串。但是,你这样做需要一些重构:
"SERIALIZED"
代表什么?你能在2个月内回忆起它的目的吗?我建议将其重构为测试套件范围的常量(或者测试方法范围,如果单个测试仅用于您使用它)。并给它正确的名称:
final String FAKED_SERIALIZER_OUTPUT = "Any random content";
Object update=new Object();
FileWriter writer=mock(FileWriter.class);
Serializer serializer=mock(Serializer.class);
when(cache.getWriter(update)).thenReturn(writer);
when(serializer.serialize(update)).thenReturn(FAKED_SERIALIZER_OUTPUT);
FileRecorder recorder=new FileRecorder(serializer);
recorder.receive(update);
verify(writer).write(FAKED_SERIALIZER_OUTPUT);
请注意,考虑到变量名称正确描述其用途,字符串的内容变得无关紧要。