Bean 在测试期间不会自动装配 (java.lang.NullPointerException)

Den*_*nov 5 java spring javabeans autowired

我的应用程序通常工作正常,但是当我运行测试或通过 maven 构建应用程序时,应用程序关闭了由于错误 java.lang.NullPointerException 的应有测试。我调试了它并发现我的服务层中的 bean 没有自动装配并且它们为空。这是我的测试课:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

所以当被调用 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
}
Run Code Online (Sandbox Code Playgroud)

我已经为该服务设置了配置文件,但我在 Idea 中有该 VM 选项:

-Dspring.profiles.active=develpment,inMemory

所以它应该有效。

Paw*_*Os. 1

为了使自动装配工作,它必须是 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