【问题标题】:Spring boot - injected map of repositories null in testsSpring Boot - 在测试中注入的存储库映射为空
【发布时间】:2020-01-08 16:20:44
【问题描述】:

在我的@RestController 中,我正在注入一个@Repositories 的映射,它都从DataBaseRepository 扩展而来。见构造函数:

@Autowired
public DatasetController(Map<String, DataBaseRepository<?, ?>> reps) {
    this.repositories = reps;
}

这在普通应用程序中就像一个魅力,但是一旦我尝试为它创建一个单元测试(使用 Mockito 的模拟),情况就不是这样了:

@RunWith(MockitoJUnitRunner.class)
public class DatasetControllerTest {

    @Mock
    private DailyTAVGRepository dailyTAVGRepository; // This extends from DataBaseRepository

    @InjectMocks
    private DatasetController datasetController;

    ...
}

在我的测试中,DatasetController 中的 this.repositoriesnull

我做错了什么或者这在单元测试中是不可能的? 提前致谢!

【问题讨论】:

  • 构造函数参数需要一个映射而不是直接存储库,因此您可以尝试使用模拟创建映射并手动创建对象 = DatasetController datasetController = new DatasetController(yourMapContainingMocks)
  • DatasetController 的优点在于它有一个构造函数。因此,您可以在测试中手动构建它,而不是尝试使用自动配置。
  • @EamonScullion 在实际应用中我从不提供/构建此地图。它是由java依赖注入自动创建的。 String 是 Classname,DataBaseRepository 是该 Classname 的适当存储库。为什么它在 Application 中有效,而在 Tests 中无效?

标签: java spring junit dependency-injection


【解决方案1】:

您可以使用 @Before 创建您的控制器,然后让 mockito 为您注入模拟。

@Before
public void init() {
    Map<String, DataBaseRepository> repos = new HashMap<>(); //you can leave this empty or add in a bunch of mocks of your own
    datasetController = spy(new DatasetController(repos));
    MockitoAnnotations.initMocks(this);

    //add your mocked repos to the repos map as needed after mocks are initialized
}

【讨论】:

  • 所以没有选项可以在测试中自动创建和自动连接该地图?在实际应用中,我从不提供/构建此地图。它是由java依赖注入自动创建的。 String 是类名,DataBaseRepository 是该类名的适当存储库。为什么它在 Application 中有效,而在 Tests 中无效?
  • 1.有一个选项。但是,这违反了单元测试的约束,它不应该启动 Spring 应用程序实例和其他服务。 2.它在Application中工作,因为Application是Spring Application。如果您想在测试中使用 Spring,您可以使用 @RunWith(SpringRunner.class) 并提供专门用于测试的 spring 配置。
【解决方案2】:

您必须使用 DailyTAVGRepositories 的地图显式实例化您的 DatasetController。

DatasetController datasetController = new DatasetController(mapWithRepositories);

您也可以尝试自动装配 DailyTAVGRepository 而不是模拟它。

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 1970-01-01
    • 2018-06-26
    • 2020-09-19
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多