我们知道@Autowired的主要优点是不会对具体实现进行硬编码。看我的代码:
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);
}
}
现在我正在尝试编写测试:
@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));
}
}
但是它不起作用! 为什么我什么时候写:
@InjectMocks private GeneralService<Bar> barService;
显示异常?依旧为以下公司工作:
@Mock private GeneralDao<Bar> barDao
我不想这样写:
@InjectMocks private BarService barService;
答案 0 :(得分:1)
由于必须测试BarService
,因此可以通过指定以下实现类来进行测试。
@InjectMocks private GeneralService<Bar> barService = new BarService(barDao);