首页 > 解决方案 > 如何模拟在静态 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 类的行为?

标签: javaspringunit-testingmockitoibatis

解决方案


也许您需要使用其他方法。如果您需要使用这些值配置应用程序,请使用@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 组件注入。代码非常相似,所以我不打算重写它。


推荐阅读