从构造函数参数模拟对象

发布于 2025-01-18 03:02:41 字数 281 浏览 0 评论 0原文

我有以下类布局:

public class Service {
  ServiceHelper helper;
  ...class methods...
}

public class ServiceHelper {
  Foo foo;
  Bar bar;
...class methods...
}

我正在为服务创建单元测试,但是我想将ServiceHelper用作“实时”类,但是ServiceHelper内的构造函数参数要被嘲笑。有没有办法通过Mockito实现这一目标?

I have the following class layouts:

public class Service {
  ServiceHelper helper;
  ...class methods...
}

public class ServiceHelper {
  Foo foo;
  Bar bar;
...class methods...
}

I am creating a unit test for Service, but I want to use ServiceHelper as a "live" class, but the constructor parameters inside the ServiceHelper to be mocked. Is there a way to achieve this via Mockito?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮光之海 2025-01-25 03:02:41

我认为您的榜样不是一个好习惯。 单元测试应尽可能小。单元测试的目的是隔离程序的每个部分,并表明各个部分是正确的。

无论如何,您仍然可以尝试这种方法。我希望它有帮助。

public class Service {

  private ServiceHelper helper;

  public Service(ServiceHelper helper) {
    this.helper = helper;
  }
}

public class ServiceHelper {

  private Foo foo;
  private Bar bar;

  // for unit testing only
  ServiceHelper(Foo foo, Bar bar) {
    this.foo = foo;
    this.bar = bar;
  }
}

和测试类:

public class ServiceTest {

  @Test
  public void your_test() {
    // arrange
    Foo mockedFoo = mock(Foo.class);
    Bar mockedBar = mock(Bar.class);
    ServiceHelper helper = new ServiceHelper(mockedFoo, mockedBar);  // the 'live' class
    Service service = new Service(helper);

    // act
    service.doSomething();

    // your assert ...
  }
}

I think your example is not a good practice. Unit testing should be as small as possible. The goal of unit testing is to isolate each part of the program and show that the individual parts are correct.

Anyway, you still can try this approach. I hope it helps.

public class Service {

  private ServiceHelper helper;

  public Service(ServiceHelper helper) {
    this.helper = helper;
  }
}

public class ServiceHelper {

  private Foo foo;
  private Bar bar;

  // for unit testing only
  ServiceHelper(Foo foo, Bar bar) {
    this.foo = foo;
    this.bar = bar;
  }
}

And the test class :

public class ServiceTest {

  @Test
  public void your_test() {
    // arrange
    Foo mockedFoo = mock(Foo.class);
    Bar mockedBar = mock(Bar.class);
    ServiceHelper helper = new ServiceHelper(mockedFoo, mockedBar);  // the 'live' class
    Service service = new Service(helper);

    // act
    service.doSomething();

    // your assert ...
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文