2017-08-30 63 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

當然你可以!有兩種方法。

在面前:

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')。 –