FreeOnGoo
FreeOnGoo

Reputation: 878

Spring Boot @Autowired by generic not work for @InjectMocks

We know that the main advantage of @Autowired is not hardcoding the concrete implementation. Look at my Code:

public interface GeneralDao<T> {
    T get(Long id);
}

@Component
public class BarDao implements GeneralDao<Bar> {
    @Override
    public Bar get(Long id) {
        Bar bar = new Bar(); // hardcode
        bar.setId(id);
        return bar;
    }
}

public interface GeneralService<T> {
    T get(Long id);
}

@Service
public class BarService implements GeneralService<Bar> {
    @Autowired
    private GeneralDao<Bar> barDao;

    @Override
    public Bar get(Long id) {
        return barDao.get(id);
    }
}

And now i'm trying to write a test:

@RunWith(MockitoJUnitRunner.class)
public class BarServiceTest {
    @Mock
    private GeneralDao<Bar> barDao;

    @InjectMocks
    private GeneralService<Bar> barService;

    @Test
    public void get() {
        Bar bar = new Bar();
        bar.setId(1L);
        when(barDao.get(1L)).thenReturn(bar);

        Bar actualBar = barService.get(1L);
        assertThat(actualBar, equalTo(bar));
    }
}

But it does not work! why when do I write:

@InjectMocks private GeneralService<Bar> barService;

show me exception? By still work for:

@Mock private GeneralDao<Bar> barDao

I do not want to write like this:

@InjectMocks private BarService barService;

Upvotes: 3

Views: 169

Answers (1)

Gaurav Srivastav
Gaurav Srivastav

Reputation: 2551

As you have to test the BarService you can do it by specifying the implementation class as below.

@InjectMocks private GeneralService<Bar> barService = new BarService(barDao);

Upvotes: 1

Related Questions