Springboot Mockito Junit 5 Command Builder模式服务单元测试

发布于 2025-01-21 23:25:46 字数 970 浏览 0 评论 0原文

我正在为我为服务类编写的代码编写单元测试。这是我班级的简短部分,因为我有一个问题:

public interface Command { public void execute(); }
public class MyServiceClass {

  private void doBusinessLogicValidation() {...}
  private void doBusinessLogicValidation2() {...}

  public void myMethod() {
     doBusinessLogicValidation();
     doBusinessLogicValidation2();

     Command myCommand = callPrivateMethodToCreateMyCommand();

     myCommand.execute();
  }

  private Command callPrivateMethodToCreateMyCommand() {
     MyObject commandObject = MyObject.builder().add("something").additional("else").build();
     return commandObject;
  }
}

上述代码很好,没有问题,并且正确使用Java访问修饰符:简短而简洁。对于单元测试,我需要覆盖CallprivateMethodTocreateMyCommand,但它是(正确)私有的。 PowerMock不支持Junit 5。

我可以将CallPrivateMethodCocreateMyCommand()更改为公众,并轻松使用Junit的()...但这打破了封装,也打破了使用私人的原因。并且不想使用受保护。

我的测试单位是myServiceClass,而不是mycommand的execute()方法。我想念什么?

任何帮助将不胜感激。

谢谢,吉姆

I'm writing the unit test to code that I wrote for a service class. Here is the short part of my class for the question(s) I have:

public interface Command { public void execute(); }
public class MyServiceClass {

  private void doBusinessLogicValidation() {...}
  private void doBusinessLogicValidation2() {...}

  public void myMethod() {
     doBusinessLogicValidation();
     doBusinessLogicValidation2();

     Command myCommand = callPrivateMethodToCreateMyCommand();

     myCommand.execute();
  }

  private Command callPrivateMethodToCreateMyCommand() {
     MyObject commandObject = MyObject.builder().add("something").additional("else").build();
     return commandObject;
  }
}

The above code is fine and works w/ no problem and uses Java access modifiers correctly: short and concise. For the unit test, I need to override the callPrivateMethodToCreateMyCommand, but it is (correctly) private. PowerMock does not support JUnit 5.

I can change the callPrivateMethodToCreateMyCommand() to public and easily use JUnit's when()...thenReturn() semantics. BUT that breaks encapsulation and the reason why one would use private. And do not want to use protected.

My unit of test is the MyServiceClass and NOT into the execute() method of myCommand. What am I missing?

Any help would be appreciated.

Thanks,Jim

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文