0

http://grepcode.com/file/repo1.maven.org/maven2/com.sun.xml.bind/jaxb-core/2.2.7/com/sun/xml/bind/api/impl/NameConverter.java#275

NameConverter is an Interface. It has a static final field called 'smart' which is an instance of an internal class declared like so:

static class Standard extends NameUtil implements NameConverter 

In our subject under test, it's referred to like so:

fieldName = NameConverter.smart.toVariableName( "an appropriate string goes here" );

Any ideas how I can mock this call? I already have:

@RunWith(PowerMockRunner.class)
@PrepareForTest({...,NameConverter.class, Standard.class,SubjectUnderTest.class,...})

Update: This has enabled me to suppress initialization of 'smart'. Now if I can find a way to set it... https://github.com/powermock/powermock/wiki/Suppress-Unwanted-Behavior

user447607
  • 5,149
  • 13
  • 33
  • 55
  • I guess you could set a different `smart` implementation via https://stackoverflow.com/questions/5385161/powermock-testing-set-static-field-of-class for your test (In case `Whitebox.setInternalState` can even change `final` fields..) or you change your code to be better testable. Needing to mock such a method feels like there is a problem with your code tbh. – zapl Feb 13 '18 at 22:49
  • Not many folks write compiler code. Bloody everything is reflection. Naturally the JAXB folks don't want anyone messing with their implementation but we are just trying to override it for test purposes so that we can establish that our code does what we think it does. – user447607 Feb 13 '18 at 22:53
  • ...anyway if this was good code, we'd probably not need PowerMock. It's legacy stuff written on virtually no budget at all. – user447607 Feb 13 '18 at 22:55
  • If you fear the output of `toVariableName` changes, test that first, then test your code using the method and you can be sure that everything is fine. Or hide the methodcall to `NameConverter.smart.toVariableName` behind an injectable object and mock that. – zapl Feb 13 '18 at 22:56
  • Huh? Why would I test JAXB? – user447607 Feb 13 '18 at 22:58
  • Doh!! https://github.com/powermock/powermock/issues/344 – user447607 Feb 13 '18 at 23:01
  • You can also do the reflection manually, https://stackoverflow.com/a/3301720/995891, or in case you can change code under test: https://gist.github.com/anonymous/9d2897f7066d6c1636c145359aa22748 or similar would solve the problem in a nicer way – zapl Feb 13 '18 at 23:22
  • Make that an answer. I'll accept. – user447607 Feb 13 '18 at 23:27
  • I tried manually but that didn't work either. Built fine in my IDE but wouldn't build in Maven. So I refactored the SUT to have a static initializer for the 'smart' variable and then provided a default access setter for testing purposes. Set it in the test with a mock object. Viola! It works. – user447607 Feb 14 '18 at 18:49

0 Answers0