Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock constructor with PowerMockito

I'm trying to mock a class constructor with PowerMockito for first time, but it doesn't work. My current code is:

public class Bar {
    public String getText() {
        return "Fail";
    }
}

public class Foo {
    public String getValue(){
        Bar bar= new Bar();
        return bar.getText();
    }

}

@RunWith(PowerMockRunner.class)
@PrepareForTest(Bar.class)
public class FooTest {
    private Foo foo;
    @Mock
    private Bar mockBar;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        PowerMockito.whenNew(Bar.class).withNoArguments().thenReturn(mockBar);
        foo= new Foo();
    }

    @Test
    public void testGetValue() throws Exception {
        when(mockBar.getText()).thenReturn("Success");
        assertEquals("Success",foo.getValue());

    }
}

The test fails because the returned value is "Fail". Where is my problem?

like image 873
Addev Avatar asked Dec 12 '16 22:12

Addev


People also ask

Can I mock a constructor?

0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes. Similar to mocking static method calls with Mockito, we can define the scope of when to return a mock from a Java constructor for a particular Java class.

How do you call a mock method in a constructor?

if your constructor is calling a method of its own class, you can fake the call using this API: // Create a mock for class MyClass (Foo is the method called in the constructor) Mock mock = MockManager. Mock<MyClass>(Constructor. NotMocked); // Faking the call to Foo mock.

How do you use PowerMockito?

To use PowerMock with Mockito, we need to apply the following two annotations in the test: @RunWith(PowerMockRunner. class): It is the same as we have used in our previous examples. The only difference is that in the previous example we have used MockitoUnitRunner.

Can we use Mockito and PowerMock together?

Of course you can – and probably will – use Mockito and PowerMock in the same JUnit test at some point of time.


1 Answers

Okey, found the answer, you need to call to

@PrepareForTest(Foo.class)

instead of

@PrepareForTest(Bar.class)
like image 185
Addev Avatar answered Sep 20 '22 15:09

Addev