2017-08-30 26 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')。 –