插件窝 干货文章 Mybatis 测试类中调用接口方法报 "Non-static method 'list()' cannot be referenced from a static context" 错误的原因和解决方法?

Mybatis 测试类中调用接口方法报 "Non-static method 'list()' cannot be referenced from a static context" 错误的原因和解决方法?

UserMapper Mapper 测试 list 622    来源:    2025-03-31

MyBatis 测试类中 "Non-static method 'list()' cannot be referenced from a static context" 错误分析

错误原因

这个错误表明你尝试以静态方式调用了一个非静态方法 list()。在 MyBatis 中,Mapper 接口的方法都是实例方法,不能直接通过类名静态调用。

常见错误场景: 1. 在测试类中直接使用 MapperInterface.list() 方式调用 2. 没有正确注入或获取 Mapper 接口的实例 3. 在静态方法中尝试调用 Mapper 方法

解决方案

方案1:获取 Mapper 实例后调用

// 正确方式:先获取Mapper实例
@Autowired
private UserMapper userMapper; // 假设UserMapper是你的Mapper接口

@Test
public void testList() {
    List<User> users = userMapper.list(); // 通过实例调用
    // 断言或其他测试逻辑
}

方案2:使用 Spring 测试支持

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testList() {
        List<User> users = userMapper.list();
        // 测试逻辑
    }
}

方案3:使用 SqlSession 获取 Mapper

@Test
public void testList() {
    try (SqlSession session = sqlSessionFactory.openSession()) {
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.list();
        // 测试逻辑
    }
}

注意事项

  1. 确保正确配置:MyBatis 和 Spring 集成配置正确
  2. 依赖注入:使用 @Autowired 或其他方式正确注入 Mapper
  3. 测试环境
    • 如果使用 Spring Boot 测试,添加 @SpringBootTest
    • 如果使用纯 MyBatis 测试,确保 SqlSessionFactory 正确初始化
  4. 静态上下文:避免在静态方法中直接使用 Mapper 方法

完整示例

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testListUsers() {
        List<User> users = userMapper.list();
        assertNotNull(users);
        assertFalse(users.isEmpty());
    }
}

通过以上方法,你应该能够解决 "Non-static method cannot be referenced from a static context" 的问题。