Mockito - 嘲弄遗留类构造函数

时间:2011-06-09 05:46:23

标签: java mocking mockito

我正在为一个通过构造函数引用遗留类的类编写JUnit。遗产类是在第三方罐子里,所以我不能重构它以使生活更轻松....

这是正在测试的课程......

public MyClass {

    public String methodToTest(String param) {
        LegacyClass legacy = new LegacyClass(param);
        *..... etc ........*
    }
}

这就是我在mockito JUnit中尝试做的事情。

public MyClassTest {

    @Test
    public void testMethodToTest() throws Exception {
        LegacyClass legacyMock = mock(LegacyClass.class);
        when(*the LegacyClass constructor with param is called*).thenReturn(legacyMock);
        *.... etc.....*
    }
}

关于我如何做到这一点的任何想法?????

3 个答案:

答案 0 :(得分:8)

LegacyClass

制作构建器
public class LegacyClassBuilder {

    public LegacyClass build(String param) {
        return new LegacyClass(param);
    }

}

这样可以对您的类进行测试,以便使用正确的参数创建LegacyClass

public MyClass {

    private LegacyClassBuilder builder;

    public setBuilder(LegacyClassBuilder builder) {
        this.builder = builder;
    }

    public String methodToTest(String param) {
        LegacyClass legacy = this.builder.build(param);
        ... etc
    }
}

测试看起来像这样:

// ARRANGE
LegacyClassBuilder mockBuilder = mock(LegacyClassBuilder.class);
LegacyClass mockLegacy = mock(LegacyClass.class); 
when(mockBuilder.build(anyString()).thenReturn(mockLegacy);

MyClass sut = new MyClass();
sut.setBuilder(mockBuilder);
String expectedParam = "LOLCAT";


// ACT
sut.methodToTest(expectedParam);

// ASSERT
verify(mockBuilder).build(expectedParam);

如果LegacyClass恰好是final,那么您需要为LegacyClass将使用的MyClass创建非最终包装。

答案 1 :(得分:5)

您可以使用PowerMockito框架:

import static org.powermock.api.mockito.PowerMockito.*;

whenNew(LegacyClass.class)
  .withParameterTypes(String.class)
  .withArguments(Matchers.any(String.class))
  .thenReturn(new MockedLegacyClass(param));

然后根据您的测试需求编写MockedLegacyClass实现。

答案 2 :(得分:0)

我认为使用Mockito模拟构造函数是不可能的。相反,我会建议以下方法:

  public MyClass {

    public String methodToTest(String param) {
     if(legacy== null){
      //when junit runs, you will get mocked object (not null), hence don't initialize 
        LegacyClass legacy = new LegacyClass(param);
      }
        *..... etc ........*
    }
}

public MyClassTest {

@InjectMock
Myclass myclass; // inject mock the real testable class
@Mock
LegacyClass legacy

@Test
public void testMethodToTest() throws Exception {    
    // when(legacy-constructor).thenReturn() ---not Required
    // instead directly mock the required methods using mocked legacy object
    when(legacy.getSomething(Mockito.any(String.class))).thenReturn(null);
        *.... etc.....*
    }
}