我很难测试一个在逻辑中使用构建器模式(BuilderClass)的类(TestClass)。我无法模拟生成器类(BuilderClass)。以下是我的逻辑的简化版本。
public class TestClass {
public int methodA() {
ExternalDependency e = BuilerClass.builder().withName("xyz").withNumber(10).build();
return e.callExternalFunction();
}
}
这是我的建筑类
public class BuilderClass {
public static BuilderClass builder() { return new BuilderClass(); }
int number;
String name;
public BuilderClass withName(String name) {
this.name = name;
return this;
}
public BuilderClass withNumber(int number) {
this.number = number;
return this;
}
public ExternalDependency build() {
return new ExternalDependency(name,number);
}
}
对于我的测试类,我将Mockito与Dataprovider一起使用。
@RunWith(DataProviderRunner.class)
class TestClassTest {
@Mock private ExternalDependency e;
@Mock private BuilderClass b;
@InjectMocks private TestClass t;
@Before public void setUp() { MockitoAnnotations.initMocks(this); }
@Test public void testMethodA() {
when(b.withName(any(String.class)).thenReturn(b); //This is not mocking
when(b.withNumber(10)).thenReturn(b); //This is not mocking
Assert.notNull(this.t.methodA()); //Control while execution is going to implementation of withName and withNumber, which should not happen right.
}
如果我错过了什么,请帮帮我。谢谢}
类似于kryger在上面的评论中所说的,您可能需要进行这样的重构:
在测试中的类中,创建一个接缝,用mock替换e
:
public class TestClass {
public int methodA() {
ExternalDependency e = buildExternalDependency("xyz", 10);
return e.callExternalFunction();
}
protected ExternalDependency buildExternalDependency(String name, int number) {
return BuilerClass.builder().withName(name).withNumber(number).build();
}
}
在测试代码中,重写测试类,用mock替换e
,并验证生成器的输入:
@RunWith(DataProviderRunner.class)
class TestClassTest {
@Mock private ExternalDependency e;
private TestClass t;
@Before public void setUp() {
MockitoAnnotations.initMocks(this);
t = new TestClass() {
@Override
protected ExternalDependency buildExternalDependency(String name, int number) {
// validate inputs:
Assert.assertEquals(10, number);
Assert.assertEquals("xyz", name);
return e; // provide the mock
}
}
}
@Test public void testMethodA() {
// TODO: mock behavior of callExternalFunction() here
Assert.notNull(this.t.methodA());
}
}
您可能需要进一步进行重构,将buildExternalDependency()移到另一个类中,该类可以被模拟并注入到TestClass的构造函数中。