java-testing by diego-tobalina/vibe-coding
npx skills add https://github.com/diego-tobalina/vibe-coding --skill java-testing<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
src/test/java/com/company/project/
└── user/
├── UserServiceTest.java # 单元测试
├── UserServiceIntegrationTest.java
└── UserRepositoryTest.java
methodName_scenarioDescription_expectedOutcome
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private UserMapper userMapper;
@InjectMocks
private UserService userService;
@Test
void create_withValidData_returnsCreatedUser() {
// 给定
UserCreateDto dto = UserCreateDto.builder()
.email("test@example.com")
.name("Test User")
.build();
User user = User.builder().id(UUID.randomUUID()).build();
when(userRepository.existsByEmail(anyString())).thenReturn(false);
when(userMapper.toEntity(any(UserCreateDto.class))).thenReturn(user);
when(userRepository.save(any(User.class))).thenReturn(user);
// 当
UserDto result = userService.create(dto);
// 那么
assertThat(result).isNotNull();
verify(userRepository).save(any(User.class));
}
@Test
void findById_nonExisting_throwsException() {
// 给定
UUID id = UUID.randomUUID();
when(userRepository.findById(id)).thenReturn(Optional.empty());
// 当/那么
assertThatThrownBy(() -> userService.findById(id))
.isInstanceOf(UserNotFoundException.class);
}
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
@SpringBootTest
@Testcontainers
class UserServiceIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
.withDatabaseName("testdb");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserService userService;
@Test
void create_persistsToDatabase() {
UserCreateDto dto = UserCreateDto.builder()
.email("test@example.com")
.name("Test")
.build();
UserDto result = userService.create(dto);
assertThat(result.getId()).isNotNull();
}
}
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void create_withValidData_returns201() throws Exception {
UserDto response = UserDto.builder().id("123").build();
when(userService.create(any())).thenReturn(response);
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"email": "test@example.com", "name": "Test"}
"""))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value("123"));
}
}
public class UserTestBuilder {
public static User.UserBuilder aUser() {
return User.builder()
.id(UUID.randomUUID())
.email("default@example.com")
.name("Default User")
.active(true);
}
}
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Testcontainers
class UserRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserRepository userRepository;
@Test
void findByEmail_existingUser_returnsUser() {
// 给定
User user = User.builder().email("test@example.com").name("Test").build();
userRepository.save(user);
// 当
Optional<User> result = userRepository.findByEmail("test@example.com");
// 那么
assertThat(result).isPresent();
assertThat(result.get().getName()).isEqualTo("Test");
}
}
# 运行所有测试
mvn test
# 运行特定测试类
mvn test -Dtest=UserServiceTest
# 运行特定测试方法
mvn test -Dtest=UserServiceTest#create_withValidData_returnsCreatedUser
# 运行覆盖率测试
mvn test jacoco:report
每周安装数
1
仓库
GitHub 星标数
1
首次出现
1 天前
安全审计
已安装于
zencoder1
amp1
cline1
openclaw1
opencode1
cursor1
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
src/test/java/com/company/project/
└── user/
├── UserServiceTest.java # Unit tests
├── UserServiceIntegrationTest.java
└── UserRepositoryTest.java
methodName_scenarioDescription_expectedOutcome
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private UserMapper userMapper;
@InjectMocks
private UserService userService;
@Test
void create_withValidData_returnsCreatedUser() {
// Given
UserCreateDto dto = UserCreateDto.builder()
.email("test@example.com")
.name("Test User")
.build();
User user = User.builder().id(UUID.randomUUID()).build();
when(userRepository.existsByEmail(anyString())).thenReturn(false);
when(userMapper.toEntity(any(UserCreateDto.class))).thenReturn(user);
when(userRepository.save(any(User.class))).thenReturn(user);
// When
UserDto result = userService.create(dto);
// Then
assertThat(result).isNotNull();
verify(userRepository).save(any(User.class));
}
@Test
void findById_nonExisting_throwsException() {
// Given
UUID id = UUID.randomUUID();
when(userRepository.findById(id)).thenReturn(Optional.empty());
// When/Then
assertThatThrownBy(() -> userService.findById(id))
.isInstanceOf(UserNotFoundException.class);
}
}
@SpringBootTest
@Testcontainers
class UserServiceIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
.withDatabaseName("testdb");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserService userService;
@Test
void create_persistsToDatabase() {
UserCreateDto dto = UserCreateDto.builder()
.email("test@example.com")
.name("Test")
.build();
UserDto result = userService.create(dto);
assertThat(result.getId()).isNotNull();
}
}
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void create_withValidData_returns201() throws Exception {
UserDto response = UserDto.builder().id("123").build();
when(userService.create(any())).thenReturn(response);
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"email": "test@example.com", "name": "Test"}
"""))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value("123"));
}
}
public class UserTestBuilder {
public static User.UserBuilder aUser() {
return User.builder()
.id(UUID.randomUUID())
.email("default@example.com")
.name("Default User")
.active(true);
}
}
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Testcontainers
class UserRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserRepository userRepository;
@Test
void findByEmail_existingUser_returnsUser() {
// Given
User user = User.builder().email("test@example.com").name("Test").build();
userRepository.save(user);
// When
Optional<User> result = userRepository.findByEmail("test@example.com");
// Then
assertThat(result).isPresent();
assertThat(result.get().getName()).isEqualTo("Test");
}
}
# Run all tests
mvn test
# Run specific test class
mvn test -Dtest=UserServiceTest
# Run specific test method
mvn test -Dtest=UserServiceTest#create_withValidData_returnsCreatedUser
# Run with coverage
mvn test jacoco:report
Weekly Installs
1
Repository
GitHub Stars
1
First Seen
1 day ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
zencoder1
amp1
cline1
openclaw1
opencode1
cursor1
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
111,800 周安装