我正在使用 java 驗證 API 來驗證 Note 類中的欄位:
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "note")
public class Note {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "date", columnDefinition = "DATE")
private LocalDate date;
@NotBlank(message = "Enter a topic")
@Column(name = "topic")
private String topic;
@NotBlank(message = "Content can't be empty")
@Column(name = "content")
private String content;
@Column(name = "type")
private NoteType noteType;
@NotNull
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
@JoinColumn(name = "user_id")
@JsonIgnore
private User user;
}
備注服務:
@Service
@AllArgsConstructor
public class NoteService {
@Autowired
private NoteRepository noteRepository;
@Autowired
private UserRepository userRepository;
public void addNote(@Valid Note note) {
note.setUser(getLoggedInUser());
if (validateNote(note)) {
noteRepository.save(note);
}
}
public List<Note> getNotes() {
return getLoggedInUser().getNotes();
}
public Note editNote(Note newNote, Long id) {
noteRepository.editNoteById(newNote, id);
return newNote;
}
public List<Note> getNotesByTopic(String topic) {
List<Note> notes = noteRepository.getNotesByTopicAndUser(topic, getLoggedInUser());
return notes;
}
public boolean validateNote(Note note) {
return validateNoteType(note.getNoteType())
&& note.getDate() != null;
}
public boolean validateNoteType(NoteType type) {
return type.equals(NoteType.NOTE)
|| type.equals(NoteType.SKILL);
}
public User getLoggedInUser() {
return userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
}
}
測驗:
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
class NoteServiceTest {
@Mock
private NoteRepository noteRepositoryMock;
@Mock
private UserRepository userRepositoryMock;
@Mock
SecurityContext mockSecurityContext;
@Mock
Authentication authentication;
private NoteService noteService;
@BeforeEach
void setUp() {
noteService = new NoteService(noteRepositoryMock, userRepositoryMock);
Mockito.when(mockSecurityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(mockSecurityContext);
}
@Test
void shouldAddNote() {
LocalDate date = LocalDate.now();
Note note = new Note(0L, date, "test", "", NoteType.NOTE, null);
noteService.addNote(note);
Mockito.verify(noteRepositoryMock).save(note);
}
}
Note 類中的欄位用戶使用@NotNull 進行注釋,并且我將一個空用戶傳遞給此便箋,但該便箋仍在保存中。當我傳遞一個空字串時也是如此。知道為什么會這樣嗎?我是單元測驗的新手
uj5u.com熱心網友回復:
I'm new to unit testing- 您完全有效的問題與單元測驗無關。@NotNull 自己什么都不做。它實際上是一份合同,內容如下:
資料成員(或任何其他使用 @NotNull 注釋的區域變數和引數)
不能為 null。
例如,而不是這個:
/**
* @param obj should not be null
*/
public void MyShinyMethod(Object obj)
{
// Some code goes here.
}
你可以這樣寫:
public void MyShinyMethod(@NotNull Object obj)
{
// Some code goes here.
}
PS
通常在編譯時使用某種注解處理器或在運行時處理它的東西是合適的。但我對注釋處理了解不多。但我確信谷歌知道:-)
uj5u.com熱心網友回復:
您需要使用 @Validated 注釋激活服務類的驗證,以便開始驗證引數。
@Service
@AllArgsConstructor
@Validated
public class NoteService {
...
請參閱服務層中的 Spring @Validated和Spring Boot:如何使用 @Validated 注釋在 JUnit 中測驗服務?更多細節。
如果由于某種原因您需要手動執行驗證,您可以隨時執行以下操作:
@Component
public class MyValidationImpl {
private final LocalValidatorFactoryBean validator;
public MyValidationImpl (LocalValidatorFactoryBean validator) {
this.validator = validator;
}
public void validate(Object o) {
Set<ConstraintViolation<Object>> set = validator.validate(o);
if (!set.isEmpty()) {
throw new IllegalArgumentException(
set.stream().map(x -> String.join(" ", x.getPropertyPath().toString(), x.getMessage())).collect(
Collectors.joining("\n\t")));
}
}
}
uj5u.com熱心網友回復:
所以你的 noteRepository 是 Mocked,所以你實際上并沒有在你的存盤庫上呼叫 save 。
Mockito.verify(noteRepositoryMock).save(note);
您在這里驗證的只是呼叫了保存,而不是成功。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432287.html
上一篇:Laravel動態驗證
下一篇:RailsERB驗證
