【问题标题】:Maven fails my unit test because of encoding issues由于编码问题,Maven 未能通过我的单元测试
【发布时间】:2013-08-24 05:19:28
【问题描述】:

我的项目中有一个基于编码的单元测试。测试在 Eclipse 中通过,但在 Maven 中失败。

我的所有文件都是 UTF-8 编码的,我在 pom.xml 中添加了以下 2 行,但测试一直失败:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

这是测试中有趣的部分。 Credentials 是一个简单的 bean,将密码存储为带有 getter/setter 的字符串(那里没有其他代码)。

AuthentificationHelper helper = new AuthentificationHelper();
// ...
String password = ":&=/?é$£";
String base64Hash = Base64.encodeString(login + ":" + password);
final String authHeader = "Basic " + base64Hash;
// ...
Credentials credentials = helper.credentialsWithBasicAuthentication(request);
assertEquals(password, credentials.getPassword());

credentialsWithBasicAuthentication 与此处执行的操作相反:

StringTokenizer st = new StringTokenizer(authHeader);
//...
String credentials = new String(Base64.decodeBase64(hashedCredentials), "UTF-8");
int p = credentials.indexOf(":");
//...
String password = credentials.substring(p + 1).trim();
return new Credentials(login, password);

这是 Maven 的输出:

Failed tests: 
   testCredentialsWithBasicAuthentication: expected:<:&=/?[?$?]> but was:<:&=/?[?$?]>

(不确定这是否相关,但我的 log4j appender 也配置为以 UTF-8 输出数据)

知道有什么问题吗? (令人惊讶的是控制台输出也没有正确显示)

解决方案(尴尬)

我使用的 Base64 类不是 Apache Commons 提供的,而是随机的。

替换:

import random.bla.bla.Base64;
// ...
String base64Hash = Base64.encodeString(login + ":" + password);

通过

import org.apache.commons.codec.binary.Base64;
// ...
String base64Hash = Base64.encodeBase64String(new String(login + ":" + password).getBytes("UTF-8"));

解决了问题。

咳嗽,咳嗽,风滚草。

【问题讨论】:

  • 这里缺少很多信息。 credentials.getPassword() 是什么?数据如何从第一个代码块传输到测试?期望值是如何声明和编码的?如果没有更多细节,这是无法回答的。
  • @Jim Garrison,稍微更新了问题,但隐藏的代码对编码没有任何好处。相关位在这里。

标签: java maven encoding utf-8 junit


【解决方案1】:

Base64.encodeString(login + ":" + password) 隐式使用字符编码(平台默认值,可以想象在 Maven 和 Eclipse 之间可能有所不同),因为它必须先将字符串转换为字节数组,然后才能对其进行哈希处理。您应该明确指定它 - 大概是 ISO-8859-1,请参阅此问题 What encoding should I use for HTTP Basic Authentication?

也有可能 Eclipse 对源文件的编码有与 Maven 不同的想法(您可以通过右键单击文件并执行属性来检查)。通常 m2e 会为您解决。

顺便说一句 - 你为什么要编写代码来处理 HTTP 身份验证?你应该使用图书馆。

【讨论】:

  • 事实上,您的回答(以及 Jim Garrison 的评论)帮助我意识到我使用的 Base64 类不是 Apache 的,而是我的项目所依赖的另一个库提供的某个随机类。我已经用解决方案更新了问题。
【解决方案2】:

我认为解决方法是转义像

这样的字符
String password = ":&=/?\u00e9$\u00a3";

【讨论】:

  • 谢谢,您的解决方案很有趣,但我偏爱用于测试可读性的解决方案。
猜你喜欢
  • 2021-05-18
  • 1970-01-01
  • 2015-04-04
  • 2011-05-08
  • 2020-06-01
  • 2022-01-17
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多