Mockito模拟构造函数示例

时间:2015-08-14 03:55:48

标签: java unit-testing mockito

我试图用Mockito实例化一个模拟对象。我在文章here中找到了两个例子,但对于像Mockito这样的新手来说,这篇文章仍然是一个非常糟糕的例子。

有人可以给我一个更好的例子来说明如何使用这两个选项中的任何一个吗?

1 个答案:

答案 0 :(得分:1)

执行PowerMockito时很简单

public class A {
    private final String name;

    public A(String name) {
        this.name= name;
    }

    public String sayHello() {
        return "Hi " + this.name;
    }}

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class MockA {

    @Test
    public void testSayHello throws Throwable {
         A a = mock(A.class); 
         when(a.sayHello()).thenReturn("Hi PowerMockito");
         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);
         assertThat(new A("I am mockcked").sayHello(), equalTo("Yes, you are!"));
    }
}

依赖

<dependencies>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito</artifactId>
      <version>${powermock.version}</version>
      <scope>test</scope>
   </dependency>
   <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>{mockito.version}</version>
    <scope>test</scope>
</dependency>
</dependencies>