java - 如何模拟在静态 Main 中创建的新对象的行为?
问题描述
有什么方法可以模拟在我的测试类静态方法中创建的对象的行为?就像,我有如下课程:
class Main{
public static void main(String[] args){
AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();
SomeMapper map = cxt.getBean(SomeMapper.class);
map.getData();
}
}
映射器“SomeMapper”是 ibatis 查询映射器,用于从数据库中获取数据。我可以使用 Mockito 框架为这个方法设置一个测试类吗?或者只能模拟映射器类或 ApplicationContext 类的行为?
解决方案
也许您需要使用其他方法。如果您需要使用这些值配置应用程序,请使用@Configuration
类:
@Configuration
public class MyCustomConfiguration{
@Autowired
SomeMapper someMapper;
//your code
}
在这种方法中,您可以在测试中模拟映射器:
@RunWith(MockitoJUnitRunner.class)
public class MyCustomConfigurationTest{
@Mock
SomeMapper someMapper;
@InjectMocks
MyCustomConfiguration configuration;
//your tests
}
如果您只需要执行一些逻辑,您还有第二个选择。您可以实现ApplicationRunner
接口。这是在启动时执行的,您可以将 bean 作为普通的 spring 组件注入。代码非常相似,所以我不打算重写它。
推荐阅读
- javascript - React 最终形式禁用没有 redux 的字段
- excel - 根据选择的超链接更新单元格值
- java - 如何从 build.xml 运行 mvn clean install
- java - 自定义 PDFTextStripper PDFbox
- java - Java 8 Stream 函数分组到 Map ,其中 value 是 Map
- excel - 如何仅在 excel vba 中选择没有标题的 usedrange 列的数据?
- vb.net - 在包含某些数据的多行文本框中查找行号
- python - 合并/追加熊猫数据框但更新重叠行
- python - 循环此代码以根据先前计算的数据帧获取新数据帧?
- javascript - 如何在 jest Node JS 中测试 AWS 中使用的 .promise() 方法内置方法