0

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?

Pablo Fallas
  • 781
  • 2
  • 7
  • 17
  • https://gualtierotesta.wordpress.com/2013/10/03/tutorial-using-mockito/ – rest_day Aug 14 '15 at 06:04
  • Possible duplicate of [Mock constructor with mockito](https://stackoverflow.com/questions/20286020/mock-constructor-with-mockito) – Miyagi May 04 '18 at 08:47

1 Answers1

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>
kuhajeyan
  • 10,727
  • 10
  • 46
  • 71
  • In the maven repository I couldn't find any PowerMockito library, there's a PowerMock I downloaded it but couldn't that PoweMockRunner.class. Can you tell me which is the correct library ? – Pablo Fallas Aug 14 '15 at 06:10
  • 1
    make sure powermock version and mockito versions are compatible. otherwise you may get classloaders issues. Better don't set explicitly mockito dependency in pom file. powermockito jar will internally pick up its compatible mokito jars. – kswaughs Aug 14 '15 at 09:15
  • @kuhajeyan why are you using PowerMockito instead of standalone Mockito? – Alex Aug 14 '15 at 16:25
  • It didn't work as I was expecting, to me it looks like mockito shouldn't be used to mock the object creation. Don't know if I'm wrong. – Pablo Fallas Aug 26 '15 at 14:52