2017-08-30 4 views
0

宣言ではなく各テストケースでテストするオブジェクトを初期化することは可能ですか?コンストラクタに渡されるパラメータがテストケースの一部であるため、宣言時にオブジェクトを初期化できません。私はようなものが必要になります。EasyMockでテストケースまでテスト対象の初期化を延期することはできますか?

@TestSubject 
    private ClassUnderTest classUnderTest; 

    @Mock 
    private Collaborator mock; 

    @Test 
    public void test12() { 
    classUnderTest = new ClassUnderTest(1, 2); 
    replay(mock); 
    Integer result = classUnderTest.work(3, 4); 
    // Assertions 
    } 

しかし、私は上記をすれば、Easymockは文句:

java.lang.NullPointerException: Have you forgotten to instantiate classUnderTest? 

私はMockBuilderを見て撮影してきましたが、私はそれがで助けることができる方法を見ていませんこの場合。

答えて

0

EasyMockは、あなたが求めているものをサポートしていません。しかし、他のテストライブラリでもサポートしています。たとえば、JMockitを使用すると:

@Test 
public void test12(
    @Injectable("1") int a, @Injectable("2") int b, @Tested ClassUnderTest cut 
) { 
    Integer result = cut.work(3, 4); 
    // Assertions 
} 
0

もちろんです。 2つの方法があります。で

前:

private ClassUnderTest classUnderTest; 

private Collaborator mock; 

@Before 
public void before() { 
    classUnderTest = new ClassUnderTest(1, 2); 
    EasyMockSupport.injectMocks(this); 
} 

@Test 
public void test12() { 
    classUnderTest = new ClassUnderTest(1, 2); 
    replay(mock); 
    Integer result = classUnderTest.work(3, 4); 
    // Assertions 
} 

それとも良い古い方法:

private ClassUnderTest classUnderTest; 

private Collaborator mock; 

@Test 
public void test12() { 
    mock = mock(Collaborator.class); 
    replay(mock); 

    classUnderTest.setCollaborator(mock); 
    classUnderTest = new ClassUnderTest(1, 2); 

    Integer result = classUnderTest.work(3, 4); 
    // Assertions 
} 
+0

まあ、これは正しいですが、質問は '@ TestSubject'の使用を前提としているようです。 EasyMockの将来のバージョンでは、少なくともJUnit 5(素晴らしい 'ParameterResolver'を持っています)では、テストメソッドで宣言された"注入可能な "パラメータのサポートを追加することができます。 –

関連する問題