-1

i am sharing a method code which contains static method 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());
                 
    }

i need to mock this method which i shared. I have tried lot of approach but getting null pointer

abhinav kumar
  • 1,487
  • 1
  • 12
  • 20

1 Answers1

0

I have written test for the method you provided.

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

Note: You can also use PowerMockito.doReturn(..).when() if you don't want to check the type of value returned

abhinav kumar
  • 1,487
  • 1
  • 12
  • 20