【发布时间】:2023-04-11 01:47:01
【问题描述】:
在 Junit 4 中,Autowired 功能运行良好。但是一旦我迁移到 Junit 5,我就无法使 Autowired 工作,并且有很多依赖项可以通过模拟每个对象来覆盖所有内容。浏览了很多网站并尝试了各种注释和依赖项,但仍然无法使其工作。 下面是我的服务实现类。
@Service
public class DetailsServiceImpl implements IDetailsService {
@Autowired
FormatBO formatBO;
public List<TestBean> fetchChargeDetails(TestBean bean){
response = //api call
List<TestBean> details = formatBO.fetchMoreDetails(response);
return details;
}
}
下面是我的测试类
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
@RunWith(JUnitPlatform.class)
@ContextConfiguration(classes = {FormatBO.class,Mapper.class})
public class SimpleImplTest {
@MockBean
Mapper mapper;
@Autowired
FormatBO formatBO;
@InjectMocks
private DetailsServiceImpl service = new DetailsServiceImpl();
static TestBean bean;
@BeforeEach
public void initData() {
bean = new TestBean();
bean.setCategoryId("1");
}
@Test
public void getBasicDetailsTest(){
service.fetchBasicDetails(bean);
}
}
FormatBO.class 是另一个类,其中有其他功能,我正在尝试自动装配,但没有发生。而是在调用 fetchMoreDetails 方法时获取空指针,因为 formatBO 为空。请帮忙解决这个问题
【问题讨论】:
标签: java junit autowired junit5 spring-boot-test