如何在 junit 测试中通过 Mockito 模拟以下方法
How to mock the following method via Mockito in junit testing
在我的服务中class我有这个
CacheLookupPolling_Darwin CacheLookupPolling_Darwin_FRAGMENT = beanFactory.getBean(CacheLookupPolling_Darwin.class);
String s = CacheLookupPolling_Darwin_FRAGMENT.cacheLookupPolling_Darwin(String, httpHeaders);
class CacheLookupPolling_Darwin 定义了一个像这样的 DefaultHttpServletRequest
private DefaultHttpServletRequest Request;
在此 class 中,函数 cacheLookupPolling_Darwin 执行以下初始化:
Request = (DefaultHttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
如何在我的测试中模拟此请求行为 class,.getRequest() 抛出 nullPointerException。
有什么建议吗?
您可以使用 @MockBean
在您的测试 class 中注入 CacheLookupPolling_Darwin
bean,然后使用 Mockito 模拟它的行为。
例如:
@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"));
}
}
在我的服务中class我有这个
CacheLookupPolling_Darwin CacheLookupPolling_Darwin_FRAGMENT = beanFactory.getBean(CacheLookupPolling_Darwin.class);
String s = CacheLookupPolling_Darwin_FRAGMENT.cacheLookupPolling_Darwin(String, httpHeaders);
class CacheLookupPolling_Darwin 定义了一个像这样的 DefaultHttpServletRequest
private DefaultHttpServletRequest Request;
在此 class 中,函数 cacheLookupPolling_Darwin 执行以下初始化:
Request = (DefaultHttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
如何在我的测试中模拟此请求行为 class,.getRequest() 抛出 nullPointerException。
有什么建议吗?
您可以使用 @MockBean
在您的测试 class 中注入 CacheLookupPolling_Darwin
bean,然后使用 Mockito 模拟它的行为。
例如:
@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"));
}
}