Rithik_Star
Rithik_Star

Reputation: 661

Exception while getting values from Mocked object using Mockito

I am writing junit using mockito for a Spring @component class. When it try to access the static field from final constant file throwing Null pointer exception.

CruserDomainTest

@RunWith(MockitoJUnitRunner.class)
public class CruserTest {
    @InjectMocks
    CruserDomain eDomain = new CruserDomain();

    @Test
    public void testGetCruseById() throws Exception,
          {
        String cCode = "AA";
        int employeeId = 21305;
        when(
                cruseRepository.getTestId(
                        anyString(), anyInt())).thenReturn(
                buildAndReturnList());
        when(
                payDomain.getRefPay(anyString(),
                        anyString(), anyString(), anyString()))
                .thenReturn(buildPay());
        CruseMember expectedResponse = eDomain.getMemberById(
                airlineCode, employeeId);


    }

CruserDomain

    //getting null pointer exception in the below line execution
//while getting the current month

 public CruseMember getMemberById(String cCode, int employeeId)
        throws Exception {

  //Some code //

        if (contractMonth.getType().equals(
                    CruseConstant.CURRENT_MONTH)) {
                currentMonthStartDate = cMonth.getStartDate();
            } else if (contractMonth.getType().equals(
                    CruseConstant.OTHER_MONTH)) {
                nextMonthStartDate = cMonth.getStartDate();
            }

CruseConstant:

public final class  CruseConstant { 

    public static final String CURRENT_MONTH = "C";
    public static final String OTHER_MONTH = "O";
    }

I tried with ReflectionTestutils but throwing exception while junit starts.

Help me on how to lookup final class static variables in the injectMocked class.

Upvotes: 0

Views: 237

Answers (2)

woezelmann
woezelmann

Reputation: 1395

It is really hard to understand your code because you have replaced the interesting parts with comments, but I would guess that you get a NPE because

contractMonth

is null. That is because you did not mock and/or forgot to define the behaviour of the class that you get the contractMonth from (CruserRepository?)

Upvotes: 0

bric3
bric3

Reputation: 42223

I strongly advise you to not mock domain objects, instead I would craft builders that can generate those objects.


Also in the code snippet @InjectMocks has no mock to inject, so injects nothing, mock fields should be declared in the test class. However I stress the point of not mocking the domain !

We've written this page on how to write good tests, I think TDD practitioners should read it, wether they use mockito or not. Lot of people contributed to refine this wiki page.

=> https://github.com/mockito/mockito/wiki/How-to-write-good-tests

Upvotes: 1

Related Questions