问题:Junit测试中@autowired的 repository为null
源代码
public class aaTestServiceTest {
//TODO 此处为null
@Autowired AwardPersonRepository awardPersonRepository;
//对Source字段去重
@Test
public void distinctAward() {
Iterable<AwardPerson> all = awardPersonRepository.findAll();
List<AwardPerson> list = new ArrayList<>();
all.forEach(a -> list.add(a));
list.stream()
.map(award -> award.getSource())
.distinct()
.forEach(item -> System.out.println(JSON.toJSONString(item, true)));
}
}
原因:少注解(@RunWith(SpringRunner.class) @SpringBootTest )
修改后:
@RunWith(SpringRunner.class) //TODO 加上这2行注解
@SpringBootTest //TODO 加上这2行注解
public class aaTestServiceTest {
@Autowired AwardPersonRepository awardPersonRepository;
//对Source字段去重
@Test
public void distinctAward() {
Iterable<AwardPerson> all = awardPersonRepository.findAll();
List<AwardPerson> list = new ArrayList<>();
all.forEach(a -> list.add(a));
list.stream()
.map(award -> award.getSource())
.distinct()
.forEach(item -> System.out.println(JSON.toJSONString(item, true)));
}
}