How to modify TestNG assertEquals?

∥☆過路亽.° 提交于 2019-12-14 03:01:31

问题


I have actual and expected objects each containing some data members. For one data member, I need to do a contains check instead of equals check and for the rest, equals check is done. Is there a way to do this ?


回答1:


Not implicitly, but you have at least the following 2 options:

  • use TestNG's assertTrue
  • use an additional library such as Hamcrest, AssertJ, etc

Dependencies:

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.9.0</version>
        <scope>test</scope>
    </dependency>

Code:

import org.testng.annotations.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertTrue;

public class MyTest {

    @Test
    public void shouldCheckStringContains() {
        String myString = "This is my string";

        // TestNG
        assertTrue(myString.startsWith("This") 
                && myString.contains("is") 
                && myString.contains("my") 
                && myString.endsWith("string"));

        // Hamcrest
        assertThat(myString, allOf(startsWith("This"),
                                   containsString("is"),
                                   containsString("my"),
                                   endsWith("string")));

        //AssertJ
        assertThat(myString).startsWith("This")
                            .contains("is")
                            .contains("my")
                            .endsWith("string");
    }
}


来源:https://stackoverflow.com/questions/49169529/how-to-modify-testng-assertequals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!