1
votes

I want non-static method of an object returned by a static factory method to return a specific result.

After I have done this setup my test code will be calling the ConnectionFactory.getConn("ABC") indirectly through another piece of code which is being tested.

PowerMockito.when(ConnectionFactory.getConn("ABC").getCurrentStatus()).thenReturn(ConnectionStatus.CONNECTED);

I get a NPE for the above statement.

  • I already have @PrepareForTest({FXAllConnectionFactory.class, ConnectionStatus.class}) at the beginning of my junit test class.

What would be the correct way of doing it?

Thanks in advance :)

1

1 Answers

0
votes

I guess there is no point in creating a fluent/chained call for your test setup.

You see:

PowerMockito.when(ConnectionFactory.getConn("ABC").getCurrentStatus()).thenReturn(ConnectionStatus.CONNECTED);

is probably meant to configure two calls:

  1. ConnectionFactory.getConn("ABC") and then
  2. getCurrentStatus() on the result of that first call

And what makes you think that PowerMockito magically knows what should be returned by that first call to getConn()?

In other words:

  1. First provide a mocked Connection object X; and configure your mocks so that getConn() returns that object
  2. In addition to that, you have to configure X to return the desired value upon a call to getCurrentStatus() ... on X!

So, the answer is actually: what you want to do isn't possible. The idea is; you specify behavior such as:

 when A.foo() is called; then return some X

There is no magic power within PowerMockito to turn

when A.foo().bar() is called thren return Y

into

when A.foo() is called, return X; when X.bar() is called return Y

You have to specify that step by step.