问题
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