"java.lang.NoSuchFieldError: FACTORY" while running Junit test in AEM codebase

 I was implementing Unit testing for a already running AEM project. After adding all the dependencies and after creation of basic structure for Sling model test class my test gets executed as expected.


@ExtendWith({ AemContextExtension.class, MockitoExtension.class })
class DummyComponentImplTest {

@BeforeEach
void setUp() {
}

@Test
public void testGetHeading() {
}

}

But soon as I add below line at line #25 in the above running test case


private final AemContext aemContext = new AemContext();

and try to run the test in terminal getting below error in the terminal's maven console.


Running com.myproject.aem.models.impl.DummyComponentImplTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.258 s <<< FAILURE! - in com.myproject.aem.models.impl.DummyComponentImplTest
[ERROR] testGetHeading Time elapsed: 0.007 s <<< ERROR!
java.lang.NoSuchFieldError: FACTORY

after doing so much google did some changes at the dependency level based on the solutions, from google search, but things didn't changed for me.

Problem was very simple but as I was not getting much stack trace either in console or in surefire-report.txt file,  not able to identify the actual cause for the problem.

When I run the same test case in eclipse, same error but the good thing was the stack trace for the error.


java.lang.NoSuchFieldError: FACTORY
at com.google.gson.Gson.<init>(Gson.java:200)
at com.google.gson.Gson.<init>(Gson.java:174)
at com.myproject.aem.models.feed.FeedVariationModel.<clinit>(FeedVariationModel.java:43)

Here I got to know the name and the location of the existing Sling model. In the particular sling model there were an unused Gson object in class scope, which was the culprit.


private static final Gson gson = new Gson();

So I had only few options like either remove the private static modifier for the object or remove this entire line since the Gson object was unused so I commented it out and finally got my easy test ride 😄


Thank you.



Comments

Popular posts from this blog

Common cause for NullPionterException or Null value in Junit test case for sling model in aem

@Inject : A discouraged sling-model annotation