java - Bean 在测试期间不会 Autowiring (java.lang.NullPointerException)

标签 java spring javabeans autowired

我的应用程序通常工作正常,但是当我运行测试或通过 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-springhttp://www.baeldung.com/spring-boot-testing

关于java - Bean 在测试期间不会 Autowiring (java.lang.NullPointerException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179018/

相关文章:

java - 在 Spring MVC Controller 中从 Blob 提供图像文件的正确方法是什么?

Java RegEx - 用开始和结束分割段落的正则表达式

java - 使用带有 hdbc 的 spring security 3.0 逐步登录示例

java - 露天注 bean

Java bean和方法实现

java - 如何在 Android 中清除 Canvas 上的绘图

java - 不从 MySQL 获取所有数据 (java)

spring - Spring 批处理中的 JdbcPagingItemReader 没有给出正确的结果

spring - 如何从 Controller 告诉 View 发生了错误? (Spring MVC)

java - BeanUtils 将 java.util.Map 转换为嵌套 bean