BlueShark
BlueShark

Reputation: 148

writing a junit test case for the calling of a method

i am using eclemma and trying to increase my test coverage:

so far this is my code:

 public RolesResponse findRolesByTenant(RolesRequest rolesRequest)
    {
        RolesResponse rolesResponse = new RolesResponse();
        List<Role> roleList = null;
        if (StringUtils.isNotBlank(rolesRequest.getTenantCode()))
        {
            roleList = roleFunctionService.getAllRolesAndFunctionsByTenant(rolesRequest.getTenantCode());

        }
        if (CollectionUtils.isNotEmpty(roleList))
        {

            rolesResponse.setRoles(roleList);
        }
        else
        {

            rolesResponse.setError(LayerContextHolder.getErrorObject());
        }

        return rolesResponse;
    }

and here is my test:

@Test
    public void findRolesByTenantTest()
    {
        RolesRequest rolesRequest = new RolesRequest();
        rolesRequest.setTenantCode("test");
        ErrorObject errorObject = new ErrorObject();


        RolesResponse rolesResponse = rolesProcessService.findRolesByTenant(rolesRequest);
        Assert.assertNull(rolesResponse.getError());

    }

the only line eclemma is highlighting in red is this one:

rolesResponse.setError(LayerContextHolder.getErrorObject());

can someone help me in constructing the final test needed to cover this line

thanks

Upvotes: 0

Views: 150

Answers (1)

Makoto
Makoto

Reputation: 106500

I'm really not a fan of your test anyway - what are you trying to prove by the error being null? That the list came back with something? Also, are you certain that your service will return the result you want in your test every single time?

Don't think of tests in terms of coverage; this will lead to brittle tests and tests that give a false sense of security. What you want to do is write tests that cover each condition that the code could encounter, and the line coverage can follow from that.

From your code, I see two cases.

  • roleFunctionService#getAllRolesByFunctionAndTenant can return a non-empty list.
    • It's implied that the resultant rolesResponse#roles contains whatever was in the list provided by the method, and this should be verified.
    • It's also implied that there is no error set on the object, so it should be null.
  • roleFunctionService#getAllRolesByFunctionAndTenant can return an empty list
    • Either the resultant rolesResponse#roles are empty or null; it'd be better if it were empty.
    • It's implied that there is an error on the object, which is specifically provided by LayerContextHolder.getErrorObject(). You should check to see that it's exactly that.

You'll get to the whole approach of writing this test through the use of a mocking framework.

Upvotes: 2

Related Questions