markdown-it
demo
Delete
Submit
clear
permalink
TODO [Assertions](https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/Assertions.html) TODO [快速看一眼JUnit 5](https://www.ithome.com.tw/voice/117883) TODO [JUnit 5 User Guide](https://junit.org/junit5/docs/current/user-guide/) ```java import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class CalculatorServiceTest { @Mock private CalculatorService calculatorService; @InjectMocks private CalculatorController calculatorController; @Test public void testAddition() { // Arrange int a = 5; int b = 10; int expectedResult = 15; when(calculatorService.add(a, b)).thenReturn(expectedResult); // Act int result = calculatorController.add(a, b); // Assert assertThat(result, is(equalTo(expectedResult))); } } ``` ```java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; public class HamcrestExamples { public static void main(String[] args) { // equalTo / is assertThat(10, Matchers.equalTo(10)); assertThat(10, Matchers.is(10)); // not assertThat(10, Matchers.not(Matchers.equalTo(20))); // nullValue / notNullValue assertThat(null, Matchers.nullValue()); assertThat("Hello", Matchers.notNullValue()); // containsString assertThat("Hello, World!", Matchers.containsString("World")); // startsWith assertThat("Hello, World!", Matchers.startsWith("Hello")); // endsWith assertThat("Hello, World!", Matchers.endsWith("!")); // greaterThan assertThat(15, Matchers.greaterThan(10)); // lessThan assertThat(5, Matchers.lessThan(10)); // greaterThanOrEqualTo assertThat(10, Matchers.greaterThanOrEqualTo(10)); // lessThanOrEqualTo assertThat(5, Matchers.lessThanOrEqualTo(10)); } } ```
html
source
debug
Fork me on GitHub