在实现构建器模式时无法模拟

时间:2015-12-16 22:36:58

标签: java junit mockito builder builder-pattern

我很难测试一个在逻辑中使用构建器模式(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.
    }

如果我错过任何帮助,请帮助我。谢谢     }

1 个答案:

答案 0 :(得分:0)

类似于kryger在上面的评论中所说的,你可能需要做一个这样的重构:

在您正在测试的课程中,创建一个接缝以用模拟替换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();       
    }

}

在测试代码中,覆盖测试类以使用模拟替换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的构造函数中进行模拟和注入。