简体   繁体   English

JUnit Mockito测试失败并显示equalTo

[英]JUnit Mockito test fails with equalTo

I am trying to understand why adding in equalTo is making my test fail. 我试图了解为什么添加equalTo会使我的测试失败。 I have recreated the problem with a simple class and test. 我已经通过简单的课程和测试重新创建了问题。

The first test passes and the second test fails. 第一次测试通过,第二次测试失败。

Sample Class 样品分类

public class Class {

Map<String, Boolean> data = new HashMap<>();

public Map<String, Boolean> getData(boolean access) {
    if (!access) 
        return null;
    return data;
}}

Test Class 测试班

public class ClassTest {

@InjectMocks
private Class testObj;

@Test
public void testGetDataNull() {
    assertThat(testObj.getData(false), is(nullValue()));
}

@Test
public void testGetDataNull2() {
    assertThat(testObj.getData(false), is(equalTo(nullValue())));
}}

The test that fails is showing this error message 测试失败显示此错误信息

Expected: is <null>
  but: was null

Q: What is the difference between these? 问:两者之间有什么区别?

Any insight is much appreciated! 非常感谢任何见解!

It is because nullValue() returns a org.hamcrest.core.isNull object. 这是因为nullValue()返回org.hamcrest.core.isNull对象。 So it is not equal to null , it is an object. 因此它不等于null ,它是一个对象。 However that object contains a matches method which will only match null , which is why is works. 但是该对象包含一个matches方法,该方法将只匹配null ,这就是为什么is作品。

As an aside, the test should probably just read assertNull(testObj.getData(false)) assertNull(testObj.getData(false)) ,测试可能应该只读取assertNull(testObj.getData(false))

Your question is actually about Hamcrest, not Mockito. 您的问题实际上是关于Hamcrest,而不是Mockito。

you're testing if the actual value, ie testObj.getData(false) , which is null , is equal to the value returned by nullValue() , which is an instance of the IsNull() matcher. 您正在测试实际值(即testObj.getData(false) ,是否为null )是否等于作为IsNull()匹配器实例的nullValue()返回的值。 An instance of IsNull is not equal to null , hence the failure. IsNull的实例不等于null ,因此失败。

I'd recommend avoiding Hamcrest, which in my opinion is harder to use correctly and less elegant than AssertJ . 我建议避免使用Hamcrest,我认为Hamcrest与AssertJ相比,更难正确使用且不够优雅。

With AssertJ, you would write 使用AssertJ,您可以编写

assertThat(testObj.getData(false)).isNull();

No static method to guess anymore, and valid autocompleted fluent assertions instead. 不再需要猜测的静态方法,而是有效的自动完成的流利断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM