Search code examples
javamockitojunit5

Mock JUnit not detecting any sonar coverage for a method that returns string


I am trying to mock below method with the intention of having sonar coverage -

public String getName(String prmTableName) {
        GetParameterRequest parameterRequest = new GetParameterRequest();
        String absParamStorePath = env.getProperty("amazon.aws.parameter") + prmTableName + "/"
                + env.getProperty("amazon.aws.env");
        parameterRequest.withName("/someurl")
        parameterRequest.withName(absParamStorePath).setWithDecryption(Boolean.valueOf(true));
        GetParameterResult parameterResult = awsSimpleSystemsManagement.getParameter(parameterRequest);
        System.out.println("Parameterstore Table Response:  " + parameterResult.getParameter().getValue());
        return parameterResult.getParameter().getValue();
    }

Below is my test implementation

@Mock
DAO dao

    @BeforeEach
        public void setup(){
            MockitoAnnotations.initMocks(this);
            mockmvc= MockMvcBuilders.standaloneSetup(dao).build();
        }
    
        @Test
        public void testName(){
    
            String value="";
            when(dao.getName("storeName"))
                    .then(t->value);
    
    
        }

but when i ran it through sonar i am getting 0% coverage. Can anyone shed some light on what could be wrong ? I am new to Mockito but i thing what is happening is that test is simply passing on empty value but it is not even hitting the required method along with required parameters.


Solution

  • If you want to test the getName method, instance of DAO should not be a mock. Mock objects are mainly used to isolate the method under test from its collaborators. Invoking a method from mock instance only does what it is told to do. Actual execution of the method doesn't happen. Hence you are seeing no coverage in sonar.

    An actual instance of the DAO class must be created to execute the method you are trying to test.

    DAO dao = new DAO();