0

I have aggregation method in service like following:

public List<Demo> demo() {
            Aggregation aggre = Aggregation.newAggregation(
                Aggregation.project("date").and(month("$date")).as("month"),
                Aggregation.group("$month").count().as("count"),
                project("count").and("month").previousOperation(),
                Aggregation.match(where("month").is(2)));

        return mongoTemplate.aggregate(aggre, "demo", Demo.class).getMappedResults();
}

How can I write a JUnit test case for the above method in spring boot?

I have tried using the following:


    @Test
    public void demoTest(){

       List<Demo> items= demoService.demo();
        Assert.assertEquals(1, items.size());
    }

I have tried the above code but it throws a NullPointerException. How can I solve this?

rohitt
  • 1,124
  • 6
  • 18
  • People will need to know what `demoService` is in your test, and any preparation you're doing on it which makes you think it has 1 demo in there. But I expect someone will point you to the 'what is a NullPointerException and how do I fix it' answer first, so: https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it/218510#218510 – BeUndead Jan 11 '21 at 11:53
  • I really don't know how can i solve this – user14982996 Jan 11 '21 at 12:02
  • Tell us which line is throwing the exception, as well as the setup details I mentioned in the other comment. – BeUndead Jan 11 '21 at 12:31
  • List items= demoService.demo(); this line shows NullPointerException. i have done aggregation of count number of items by month. – user14982996 Jan 11 '21 at 13:31
  • Which is also why I asked for 'what `demoService` is in your test'. How are you initialising it? Is `demoService` `null` at the point you're calling it? Are you passing it a `null` `mongoTemplate` when you create one, etc. – BeUndead Jan 11 '21 at 13:41
  • But the answer I linked above goes into _great_ detail about what a `NullPointerException` is and how to find the cause of it. – BeUndead Jan 11 '21 at 13:43

0 Answers0