I'm new to testing framework I have to test a function which have involves storing data from Db into list.
Note: I don't have any POJO Class or Entity class for this.
I'm just connecting to the database. Following is the method for which I want to write test cases. I have basic knowledge about Junit and Mockito. I know if we have MongoRepository or template then we can use the @Mock annotation and can mock the repo which we have created. But in my case I don't know how I should mock the DB.
Following is the function --
public List<FriendDetails> fetchStationIds() {
AtomicInteger count = new AtomicInteger();
List<FriendDetails> list = new ArrayList<>();
MongoDatabase database = mongoClient.getDatabase("Friends");
MongoCollection<Document> collection = database.getCollection("Friend");
BasicDBObject filter = new BasicDBObject("$and", Arrays.asList(new BasicDBObject("name", new BasicDBObject("$regex", "^Ram")).append("id", new BasicDBObject("$regex", "Shyam$"))));
collection.find(filter).forEach((Consumer<Document>) doc -> {
count.getAndIncrement();
String name = (String) doc.get("name");
if(name != null) {
String nameSpace = name.substring(0, name.indexOf("a") + 1);
String temp = name.substring(name.indexOf("a") + 1);
Document FriendValue1 = ((ArrayList<Document>) doc.get("Main_array")).get(0);
ArrayList<Document> arrayList = (ArrayList<Document>) FriendValue1.get("Main_ArrayPart2");
if(!arrayList.isEmpty()) {
Document FriendValue2 = arrayList.get(0);
Long number = (Long) FriendValue2.get("number");
String pinCode = (String) FriendValue2.get("pincode");
FriendDetails friendDetail = new FriendDetails(nameSpace, temp, number, pincode);
if (listDoesNotContain(list, friendDetail.toString())) {
list.add(friendDetail);
}
}
}
});
return list;
}
Test case I tried to write --
@Mock
private MongoClient mockClient;
@Mock
private MongoCollection mockCollection;
@Mock
private MongoDatabase mockDB;
@InjectMocks
private FriendsDetails wrapper;
@Before
public void initMocks() {
when(mockClient.getDatabase(anyString())).thenReturn(mockDB);
when(mockDB.getCollection(anyString())).thenReturn(mockCollection);
wrapper.initName();
MockitoAnnotations.initMocks(this);
}
@Test
void testFetch(){
FindIterable iterable = mock(FindIterable.class); //which class I should mock
MongoCursor cursor = mock(MongoCursor.class);
Document bob = new Document("_id",new ObjectId("579397d20c2dd41b9a8a09eb"))
.append("firstName", "Bob")
.append("lastName", "Bobberson")
.append("number","36273872")
.append("pincode", "677");
when(mockCollection.find()))
.thenReturn());
assertEquals(expected, actual));
}
}