简体   繁体   English

模拟参考对象

[英]Mock reference objects

How do you avoid creating superfluous Strings when unit testing? 在单元测试时,如何避免创建多余的字符串?

For example the String "SERIALIZED" seems a bit unnecessary and arbitrary..what would you use instead? 例如,字符串“ 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");

I wouldn't call strings you use to verify whether your test passes superfluous . 我不会打电话给您用来验证您的测试是否通过了多余的字符串。 However, way you do it calls for a bit of refactoring: 但是,执行此方法需要一些重构:

  • what "SERIALIZED" stands for? "SERIALIZED"代表什么? Will you be able to recall its purpose in, say, 2 months? 您可以在两个月内回忆起它的目的吗?
  • you use same string twice, simple typo (which happen) will break your test. 您使用相同的字符串两次,简单的错字(发生)将破坏您的测试。 And that's something you want to avoid 那就是你要避免的事情

I suggest refactoring it into a test suite-wide constant (or test method-wide , if that single test is only place you use it). 我建议将其重构为整个测试套件范围内的常数(如果仅在您使用单个测试的地方,则将其重构为整个 测试方法 范围内的常数)。 And give it proper name: 并为其命名:

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

Note that content of the string becomes irrelevant, considering variable name describes its purpose correctly. 请注意,考虑到变量名称正确描述了其用途,字符串的内容变得无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM