我有一個服務類,它查詢CRUDRepository基于id, name and money.
如果資料存在,它會提取錢,給它加 100 并將更新的物件保存在存盤庫中。如果資料不存在,它將創建一個新物件并將其保存在存盤庫中。
Person.java
@Value
@Builder
public class Person {
private final UUID id;
private final String name;
@With
private final BigDecimal money;
}
Service.Java
private Person updateOrSave(final UUID id, final String name) {
final Optional<Person> existingPerson = myRepo.findByIdAndName(id, name);
if (existingPerson.isPresent()) {
updatedPerson = existingPerson.withMoney(existingPerson.getMoney().add(new BigDecimal(100)));
return myRepo.save(updatedPerson);
} else {
return myRepo.save(Person.builder()
.id(id)
.name(name)
.money(money)
.build()));
}
}
我需要為這種存在資料的場景撰寫單元測驗。我能寫測驗用例,但問題是myCrudRepository.save()回報null。
所以這就是我測驗它的方式。
Test.java
@ExtendWith(MockitoExtension.class)
class PersonTest {
@Mock
private MyRepo myRepo;
@InjectMocks
private Service service;
@Test
void updateExistingMoney() {
final UUID id = UUID.randomUUID();
final String name = "TestName";
final Optional<Person> person = Optional.of(Person.builder()
.id(id)
.name(name)
.money(new BigDecimal(10))
.build());
final Person finalPerson = Person.builder()
.id(id)
.name(name)
.money(new BigDecimal(110))
.build()
when(myRepo.findByIdAndName(id, name))
.thenReturn(person);
service.updateOrSave(id, name);
verify(myRepo).save(finalPerson);
}
Is this correct way of testing or is it wrong ?
uj5u.com熱心網友回復:
您可以使用引數捕獲器的概念來捕獲作為引數傳遞給模擬存盤庫的物件。
@ExtendWith(MockitoExtension.class)
class PersonTest {
@Mock
private MyRepo myRepo;
@InjectMocks
private Service service;
@Captor
private ArgumentCaptor<Person> personCaptor;
@Test
void updateExistingMoney() {
final UUID id = UUID.randomUUID();
final String name = "TestName";
final Optional<Person> person = Optional.of(Person.builder()
.id(id)
.name(name)
.money(new BigDecimal(10))
.build());
final Person finalPerson = Person.builder()
.id(id)
.name(name)
.money(new BigDecimal(110))
.build()
when(myRepo.findByIdAndName(id, name))
.thenReturn(person);
service.updateOrSave(id, name);
verify(myRepo).save(personCaptor.capture());
final Person actual = personCaptor.getValue();
// Do checks on expected person vs. the actual one
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/378265.html
標籤:爪哇 弹簧靴 朱尼特 crud-repository
