Issue
In my service class i have this
CacheLookupPolling_Darwin CacheLookupPolling_Darwin_FRAGMENT = beanFactory.getBean(CacheLookupPolling_Darwin.class);
String s = CacheLookupPolling_Darwin_FRAGMENT.cacheLookupPolling_Darwin(String, httpHeaders);
the class CacheLookupPolling_Darwin defines a DefaultHttpServletRequest like this
private DefaultHttpServletRequest Request;
In this class the function cacheLookupPolling_Darwin performs the following initialization:
Request = (DefaultHttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
how can i mock this Request behaviour in my test class, the .getRequest() throws a nullPointerException.
Any advice?
Solution
You can inject the CacheLookupPolling_Darwin
bean in your test class using @MockBean
and then mock it's behavior with Mockito.
For example:
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class SomeTestSuite {
@MockBean
private CacheLookupPolling_Darwin cacheLookupPolling_Darwin;
@Test
public void someTest() {
given(cacheLookupPolling_Darwin.cacheLookupPolling_Darwin(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.willReturn("mocked return value"));
}
}
Answered By - flaviuratiu
Answer Checked By - Clifford M. (JavaFixing Volunteer)