stubbing a private field of mocked object

6,354 views
Skip to first unread message

Murali

unread,
Feb 6, 2010, 3:56:05 AM2/6/10
to mockito
Hi,


I have a class A as follows

public class A{

@Inject
private B b;

public String doStuff(){
//Do some stuff, which utlizes b
}

}

I know how to mock A and B. I am not clear how to strub A.b with my
mock B. Can somebody please help me?

Thanks in advance.

szczepiq

unread,
Feb 6, 2010, 9:16:31 AM2/6/10
to moc...@googlegroups.com
Sure,

I would do either of:
- make the 'b' field package-protected
- or add a setter for the 'b' field
so that I can set it from the test...

No need for any mocking.

Cheers,
Szczepan Faber

> --
> You received this message because you are subscribed to the Google Groups "mockito" group.
> To post to this group, send email to moc...@googlegroups.com.
> To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mockito?hl=en.
>
>

Moandji Ezana

unread,
Feb 6, 2010, 5:34:17 PM2/6/10
to moc...@googlegroups.com
To add to Szcezpan's list, you could also:

- Add a constructor that takes 'b'
- Inject 'b' yourself via reflection.

I generally use the constructor option, as it feels most natural to me.

Moandji

James Carr

unread,
Feb 6, 2010, 6:55:51 PM2/6/10
to moc...@googlegroups.com
I actually posted on this predicament a couple months ago:

http://blog.james-carr.org/2009/12/29/express-your-dependencies/

Thanks,
James

Malte Finsterwalder

unread,
Feb 9, 2010, 5:19:38 AM2/9/10
to mockito
You can also use EasyGloss (https://easygloss.dev.java.net). EasyGloss
can inject private fields for you.

Though you might need to extend it a bit to understand the @Inject
Annotation. It might only know @EJB, but it should be no problem to
add @Inject as well.

Greetings,
Malte

Reply all
Reply to author
Forward
0 new messages