0

我想知道测试工厂行为代码的最佳实践是什么。在我的例子中,工厂创建了一些依赖实例,这些实例将传递给 FooBar 实例的构造函数。

public class FooBarFactory {
  private Dependency1 dependency1;
  private Dependency2Factory factory;

  public FooBarFactory(Dependency1 dependency1, Dependency2Factory factory) {
    this.dependency1 = dependency1;
    this.factory = factory;
  }

  public FooBar create() {
    return new FooBar(dependency1, factory.create(), new Dependency3());
  }
}

依赖关系可以由其他一些工厂创建,也可以由被测工厂直接创建。

为了测试工厂行为,我现在要做的是在 FooBar 中创建一些受保护的 getter 来检索依赖项,这样我就可以断言构造函数注入并且正确创建了依赖项。

这是我不确定的地方。为了测试的目的添加一些吸气剂让我有点困扰,因为它破坏了封装。我也可以使用反射来检索字段值,但我通常认为这是不好的做法,因为它很容易被破坏。

任何人都可以提供有关此问题的见解吗?

4

4 回答 4

1

一种解决方案是模拟FooBar类并验证构造函数调用,通过该构造函数调用创建返回的实例FooBarFactory#create()。使用 JMockit 模拟 API,这样的测试看起来像:

public class FooBarFactoryTest
{
    @Injectable Dependency1 dep1;
    @Injectable Dependency2 dep2;
    @Cascading @Injectable Dependency2Factory dep2Factory;
    @Mocked FooBar mockFooBar;
    @Tested factory;

    @Test
    public void createFooBarWithProperDependencies()
    {
        assertNotNull(factory.create());

        new Verifications() {{ new FooBar(dep1, dep2, (Dependency3) withNotNull()); }};
    }
}
于 2012-07-09T17:18:57.493 回答
0

As a Unit-Test you should test your unit (class) and just this.

The value created by a factory inside your factory should be tested on its unit-test. For example on your situation, it doesn't make sense to test what dependency2Factory return, because in order to FooBar work, Dependency2Factory should work too (in case it isn't configurable), if it is configurable you can provide your own mock and this would be enough.

And Dependency2Factory should be tested on a separated Unit-Test.

You don't test if the method List.get(int index) works every time you use a list in your implementation right?

于 2012-07-09T14:10:54.213 回答
0

How about mocking? Mock every dependency required to run the tested piece of code. There are a few good mock frameworks like mockito.

于 2012-07-09T14:45:14.267 回答
0

我想我想到的建议是反过来注入 FooBarFactory 的依赖项,以便它将 Dependency1 和 Dependency2Factory 作为构造函数参数或作为 setter 方法中的值。

于 2012-07-09T14:16:17.060 回答