如何使用 spring boot SpringJUnit4ClassRunner 模拟方法,其中使用 mongo 模板,方法包含静态调用

how to mock a mehod using spring boot SpringJUnit4ClassRunner where mongo tamplate is used where the method contains static call

我正在分享一个包含静态方法调用的方法代码。

public List<String> getTestContent() {
        
        DistinctIterable<String> distinctIterable = mongoTemplate.getCollection("test-doc").distinct("testcontent",String.class);
         return StreamSupport.stream(distinctIterable.spliterator(),false).collect(Collectors.toList());
                 
    }

我需要模拟我分享的这个方法。我尝试了很多方法但得到空指针

我已经对你提供的方法进行了测试

@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()