为了用Guice注入一个类,必须将替换类作为对象参数传递给构造函数?

时间:2016-02-11 21:44:31

标签: java mocking guice

为了使用Guice注入一个类,是否必须将替换类作为对象参数传递给构造函数?我认为这是"当然",但我想我会问。

我用两个构造函数编写了一个测试类(CUT)。一个构造函数接受一个参数,一个类型依赖于组件(DOC)的对象。另一个构造函数调用第一个,传递一个新的DOC()。单元测试使用注入器指示CUT使用MockDOC而不是DOC。当我删除默认的CUT()时,单元测试会出现运行时错误: com.google.inject.internal.ComputationException:java.lang.NoClassDefFoundError:org / objectweb / asm / ClassVisitor

代码:

//The class under test:
public class CUT {
    DOC m_DOC;

    @Inject
    public CUT(DOC doc)
    {
        m_DOC = doc;
    }

    // When this ctor is added, there is a run time error:
    // com.google.inject.internal.ComputationException: java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
//    @Inject
//    public CUT()
//    {
//       this(new DOC());
//    }

    public boolean getVal()
    {
        return m_DOC.getVal();
    }
}

    // The depended-on-component:
public class DOC {
    @Inject
    public DOC()
    {

    }

    // The REAL DOC returns 'true' MockDOC will return false
    public Boolean getVal()
    {
        return true;
    }
}

模拟DOC:

     // This is the class we want CUT to call during unit test
class MockDOC extends DOC
{
    @Override
    public Boolean getVal()
    {
        // Real DOC returns 'true'. We return false so unit tester knows we got injected
        return false;
    }
}

使用MockDOC测试CUT的单元测试:

    // Test the CUT class by substituting a mock for CUT's DOC
public class CUTTest {

    @Test
    public void testGetVal() throws Exception {
        // Direct Guice to inject our MockDOC for CUT's use of DOC
        Injector m_injector = Guice.createInjector(new CUTTestModule());

        // Ask Guice to create a CUT object
        CUT cut = m_injector.getInstance(CUT.class);

        // The DOC returns 'true', while the mock DOC returns 'false. So we'll get 'false' if the injection
        // succeeded
        assertEquals(cut.getVal(), false);
    }

    // The class that we will pass to Guice to direct its injection
    class CUTTestModule implements Module {
        public CUTTestModule()
        {
            super();
        }

        @Override
        public void configure(Binder binder) {
            binder.bind(DOC.class).to(MockDOC.class);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您也可以在字段上使用Guice注入。

但是关于你的主要问题...为什么要将@Inject注释添加到默认构造函数(没有参数的那个)?没有要注入的参数。

// When this ctor is added, there is a run time error:
    // com.google.inject.internal.ComputationException: java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
//    @Inject
//    public CUT()
//    {
//       this(new DOC());
//    }

我会删除@Inject