Search code examples
javamockitojunit4generic-collections

unable to mock generic object creation


I want to mock dao creation for following method.

private ReturnType createTenant(){

TenantDto tenantDto = new TenantDto();
        TenantGroupDto tenantUserGroupDto = new TenantGroupDto(DEFAULT_USER_GROUP_NAME,Type.HUMAN,DEFAULT_USER_GROUP_DESCR, true);
        TenantGroupDto tenantDeviceGroupDto = new TenantGroupDto(DEFAULT_DEVICE_GROUP_NAME,Type.DEVICE,DEFAULT_DEVICE_GROUP_DESCR, true);

        Set<TenantGroupDto> tenantGroups = new HashSet<TenantGroupDto>();

        tenantGroups.add(tenantUserGroupDto);
        tenantGroups.add(tenantDeviceGroupDto);
        tenantDto.setTenantGroup(tenantGroups);          
        tenantDto = tenantDao.create(tenantDto);
        return someOtherOperation(tenantDto);
}

I'm able to mock rest of the things however. I'm unable to mock generic creation.

i.e.

Set<TenantGroupDto> tenantGroups = new HashSet<TenantGroupDto>();

It is required to be mocked since tenantGroups is parameter to

tenantDao.create(tenantDto);

Most of the links/questions I search about are when the generic object gets returned from some method. I couldn't find any solution to creation of generic object. Any help is appreciated.
Thx in Advance.


Solution

  • This is how to create a mock of a generic class.

    @Mock
    Set<TenantGroupDto> tenantGroups 
    
    @Before
    public void init(){
    MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void myTest(){
    when(tenantGroups....
    }