我的应用程序通常工作正常,但是当我运行测试或通过 maven 构建应用程序时,应用程序正在关闭由于错误 java.lang.NullPointerException 进行的测试。我调试了它并发现我的服务层中的 bean 没有 Autowiring 并且它们为空。
这是我的测试课:
public class CompanyServiceSimpleTest {
private CompanyService companyService;
@Before
public void setUp() {
companyService = new CompanyServiceImpl();
}
// Here is sample test
@Test
public void testNumberOfCompanies() {
Assert.assertEquals(2, companyService.findAll().size());
}
}
companyService 已初始化,但其中的 bean 未初始化。这是 CompanyServiceImpl:
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyRepository companyRepository; // is null
@Autowired
private NotificationService notificationService; // is null
@Override
public List<CompanyDto> findAll() {
List<CompanyEntity> entities = companyRepository.find(0, Integer.MAX_VALUE);
return entities.stream().map(Translations.COMPANY_DOMAIN_TO_DTO).collect(Collectors.toList());
}
// ... some other functions
}
所以当被调用 companyRepository.find() 应用程序崩溃。这是存储库类:
@Repository
@Profile("inMemory")
public class CompanyInMemoryRepository implements CompanyRepository {
private final List<CompanyEntity> DATA = new ArrayList<>();
private AtomicLong idGenerator = new AtomicLong(3);
@Override
public List<CompanyEntity> find(int offset, int limit) {
return DATA.subList(offset, Math.min(offset+limit, DATA.size()));
}
// ... some others functions
}
我已经为该服务设置了配置文件,但我在 Idea 中有该 VM 选项:
-Dspring.profiles.active=develpment,inMemory
所以它应该有效。
最佳答案
为了使 Autowiring 工作,它必须是一个 Spring 集成测试。您必须使用以下内容注释您的测试类:@RunWith(SpringJUnit4ClassRunner.class)
和 @ContextConfiguration(classes = {MyApplicationConfig.class})
如果它是 Spring Boot 应用程序,例如:@RunWith(SpringJUnit4ClassRunner.class)
和 @SpringBootTest(classes = {MyApp.class, MyApplicationConfig.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
有关此主题的更多信息:http://www.baeldung.com/integration-testing-in-spring和 http://www.baeldung.com/spring-boot-testing
关于java - Bean 在测试期间不会 Autowiring (java.lang.NullPointerException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179018/