找到你要的答案

Q:Mockito mock constructor example

Q:mockito模拟构造函数的例子

I'm trying to instantiate a mock object with Mockito. I found two examples in the article here, still this article is a very bad example for a newbie like me in Mockito.

Can somebody give me a better example of how it is done with either of the two options?

我试图实例化一个模拟对象与Mockito。我发现在这里的第二例,还是这篇文章是为像我这样的新手在Mockito一个很坏的榜样。

有人能给我一个更好的例子,它是如何做的两个选项之一?

answer1: 回答1:

Simple when doing 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

<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>

简单的时候,做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>
java  unit-testing  mockito