代码之家  ›  专栏  ›  技术社区  ›  riorio

在单元测试[duplicate]中运行时,Spring boot组件面临空指针

  •  0
  • riorio  · 技术社区  · 7 年前

    我的Spring Boot应用程序有 Controller 使用 Service SharkMaster )使用来自 properties

    当我以常规模式运行应用程序时,它可以正常工作。

    但是,当尝试为控制器类运行单元测试并为其提供模拟时 service 它试图创建真正的SharkMaster bean,但由于无法从配置中找到值而失败。

    several posts 读一些 blog posts 关于类似的问题,但在目前阶段,应用程序正在崩溃 NullPointer 尝试在单元测试模式下运行时。

    @Configuration
    public class SharkMaster{
    
    @Value("${sharkName}")
    private String sharkName;
    
    public SharkMaster(){
      // sharkName is null here and the NullPointer is thrown
    }
    

    控制器测试类:

    @RunWith(SpringRunner.class)
    @WebMvcTest(SharkController.class)
    @ContextConfiguration(classes = {SharkMaster.class})
    @TestPropertySource("classpath:application-test.yml")
    public class SharkControllerTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @MockBean
    private SharkService sharkService;
    

    我试着加上 @PropertySource("classpath:application-test.yml")

    我相信这个问题和 this one ,因为这里的情况是在单元测试阶段。

    1 回复  |  直到 7 年前
        1
  •  1
  •   pvpkiran    7 年前

    删除您的 @ContextConfiguration 像这样试试。

    @RunWith(SpringRunner.class)
    @WebMvcTest(controllers = SharkController.class)
    public class SharkControllerTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @InjectMocks
    private SharkService sharkService;
    
    @Mock
    private SharkMaster sharkMaster;
    
    .......
    }