Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMock access private static members

How I can access the following private static field foo by PowerMock. I just want to verify that Foo for example is not null and I can't refactor the code by adding getters.

public class Bar{

   private static Foo foo = new Foo();


}

I try to use this but it does not work:

Foo foo = Whitebox.getInternalState(bar, "foo");
like image 817
Daoud Shaheen Avatar asked Sep 17 '16 17:09

Daoud Shaheen


2 Answers

Whitebox.getInternalState(Foo.class, "FIELD_NAME");
like image 157
kreker Avatar answered Nov 09 '22 14:11

kreker


Verifying that a private field has a certain content translates to: testing internal implementation details. Sure, that is possible, but it also makes your tests very fragile - slight changes (like: refactoring) to the production code, and your tests fail; although you probably did not change the contract of your class under test.

And you see - I am pretty sure that it somehow makes a difference within your class under test if that field is null or not. Meaning: some behavior your class under test will be different for those two scenarios.

Thus my suggestion: see if you can avoid Powermock here - by finding other ways to "assert" something within your production class to test if that field is null.

Seriously: if the content of that field doesn't influence any observable behavior of your class under test - what would be the purpose of that field in the first place?!

like image 33
GhostCat Avatar answered Nov 09 '22 13:11

GhostCat