junit assertEquals忽略大小写

编程入门 行业动态 更新时间:2024-10-09 15:17:03
本文介绍了junit assertEquals忽略大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我只是从c# - > java移动。我需要使用junit编写一些测试。 在我的测试中,我需要比较两个字符串,看它们是否匹配。 所以我们也有Assert.assertEquals,但这是区分大小写的。我怎样才能使它不区分大小写? 我需要的是:

blabla.equals(BlabLA)

返回true。

所以在C#中,我们曾经有过:

public static void AreEqual( string expected, string actual, bool ignoreCase, string message )

我很快就通过Junit文档,但我似乎无法找到这样的东西。

解决方案

我发现 Hamcrest 提供的断言必须比默认的 JUnit 断言更好。 Hamcrest提供了更多选项,并在失败时提供更好的消息。一些基本的 Hamcrest 匹配器内置于 JUnit 和 JUnit 已内置内置的 assertThat 不是全新的东西。请参阅 JUnit API中的 hamcrest.core 包此处。尝试 IsEqualIgnoringCase ,如下所示。

assertThat(myString,IsEqualIgnoringCase.equalToIgnoringCase(expected));

使用静态导入时,这将是

assertThat(myString,equalToIgnoringCase(expected));

如果你想真正想要的话:

assertThat(myString,is(equalToIgnoringCase(expected)));

这样做的一个优点是失败会说明期望someString但是someOtherString 。与相反,当使用 assertTrue 时,预期true得到假。

im just moving from c# -> java. I need to write some tests using junit. In my test i need to compare two strings to see if they match. So we also have the Assert.assertEquals, but this is case sensitive. How can i make it case insensitive? What i need is:

"blabla".equals("BlabLA")

to return true.

So in C#, we used to have :

public static void AreEqual ( string expected, string actual, bool ignoreCase, string message )

I was quickly going thru Junit docs, but i can't seem to find anything like this.

解决方案

I find that Hamcrest provides must better assertions than the default JUnit asserts. Hamcrest gives MANY MANY more options and provides better messages on failure. Some basic Hamcrest matchers are built into JUnit and JUnit has the assertThat built in so this is not something totally new. See the hamcrest.core package in the JUnit API here. Try IsEqualIgnoringCase which would look like this.

assertThat(myString, IsEqualIgnoringCase.equalToIgnoringCase(expected));

With static imports this would be

assertThat(myString, equalToIgnoringCase(expected));

if you want to get really fancy you would do:

assertThat(myString, is(equalToIgnoringCase(expected)));

One of the advantages of this is that a failure would state that expected someString but was someOtherString. As opposed to expected true got false when using assertTrue.

更多推荐

junit assertEquals忽略大小写

本文发布于:2023-11-11 08:27:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577882.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大小写   junit   assertEquals

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!