本文介绍了maven 测试以东方语言字符失败,而 IDEA 成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是测试类:

@AutoConfigureTestDatabase
@Sql(value = {"classpath:/ut_user_init.sql"})
public class UserControllerTest extends MockMvcTest {
    @Test
    @WithUserDetails(value = MockData.ADMIN_USERNAME, userDetailsServiceBeanName = "mockUserDetailsService")
    public void testGetUser() throws Exception {}
}

UserController类:

@RequestMapping("list")
public String list(Model model) {
   userService.findByName("[An Eastern character]")
}

UserService 类中:

User findByName(String name) {
     return userRepository.findByName(name); // name is in Eastern language.
}

这是ut_user_init.sql

INSERT INTO `user` VALUES ('32', '[The Eastern character]');

这是有效的pom.xml:

<maven.compiler.encoding>utf-8</maven.compiler.encoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

现在奇怪的是:如果我使用 IDEA,Service 类返回一个查找结果,但是如果我使用 mvn test -Dtest=path.to.TestClass,它会失败,因为返回是空值.但是如果我打印 userRepository.findAll().size() 的结果,我可以看到它打印了 sql 文件中列出的正确数量的记录.我还尝试打印 userRepository.findOne(32L) 的结果,在 MinGW(windows 使用 GDB 用于东方语言,而源文件为 UTF-8)和 Linux 打印 名称.虽然 IDEA 没有这个问题,但它会返回结果并按原样打印东方字符.为什么 mvn 和 IDEA 的行为不同,导致 mvn 失败的原因以及如何解决?谢谢.

Now the odd thing is: if I use IDEA the Service class returns a finding result, but if I use mvn test -Dtest=path.to.TestClass, it would fail because the return is null. But if I print the result of userRepository.findAll().size() I can see that it prints a correct number of records listed in sql file. And I also tried printing result of userRepository.findOne(32L), in both MinGW (windows uses GDB for Eastern languages while the source files are in UTF-8) and Linux prints random code for the name. While IDEA does not have this problem, it returns the finding and it prints the Eastern Character as it is. Why mvn and IDEA behaves differently, and what caused mvn fail, and how to solve this? Thanks.

推荐答案

我猜当您从命令行运行时,它会采用您的系统默认编码,可能不是 UTF-8.

I am guessing that when you run from the command line it is taking your system default encoding, which may not be UTF-8.

试试这个:

mvn test -DargLine="-Dfile.encoding=UTF-8" -Dtest=MyTestClassName

这篇关于maven 测试以东方语言字符失败,而 IDEA 成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:36