如何解决如何使用Spring Boot SpringJUnit4ClassRunner模拟方法,其中在使用mongo tamplate的方法中包含静态调用
我正在共享一个包含静态方法调用的方法代码。
ISSUER = b"RSA AUTHORITY"
SUBJECT = b"Domain.com"
SUBJECT_PUBLIC_KEY = rsa_public_key_bytes
all_data = {}
all_data["SUBJECT"] = subject_name
all_data["SUBJECT_PUBLIC_KEY"] = subject_public_key
all_data["ISSUER"] = issuer_name
我需要模拟这个我共享的方法。我尝试了很多方法,但是得到空指针
解决方法
我已经对您提供的方法进行了测试。
@RunWith(SpringJunit4ClassRunner.class)
public class MyTestClass
{
@MockBean
private MongoTemplate mongoTemplate;
@MockBean
private MongoCollection<Document> mongoCollection;
@MockBean
private DistinctIterable<String> distinctIterable;
@InjectMocks
private ServiceImpl service;
@Before
public void setUp()throws Exception{
MockitoAnnotations.openMocks(this);
}
public void testGetTestContent(){
List<String> list = new ArrayList<>();
list.add("test1");
list.add("test2");
Spliterator<String> spliterator = list.spliterator();
PowerMockito.when(mongoTamplate.getCollection(Mockito.eq("test-doc"))).thenReturn(mongoCollection);
PowerMockito.when(mongoCollection.distinct(Mockito.eq("testcontent"),Mockito.eq(String.class))).thenReturn(distinctIterable);
PowerMockito.when(distinctIterable.spliterator()).thenReturn(spliterator);
Assert.assertEquals(2,service.getTestContent().size());
}
}
注意:如果您不想检查返回值的类型,也可以使用PowerMockito.doReturn(..)。when()。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。