简体   繁体   中英

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");
Whitebox.getInternalState(Foo.class, "FIELD_NAME");

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?!

您可以为此使用 Spring 的ReflectionTestUtils.getField()

Foo foo = ReflectionTestUtils.getField(Bar.class, "foo");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM