我想檢查模擬 JPA 存盤庫是否會回傳所有元素。我創建了 3 個物體并對其進行了初始化,然后創建了串列并將這些模型放入該串列中。之后,寫下宣告:
when(pasteboxJPARepository.findAll()).thenReturn(entities);
看起來,在呼叫 findAll() 方法之后,我將獲得物體串列。是的,我明白了,但是除了第一個元素之外,所有元素都是空的,不知道它可以是什么(最后的控制臺螢屏)。
測驗類
@SpringBootTest
public class PasteboxServiceTests {
@Autowired
PasteboxService pasteboxService;
@MockBean
PasteboxJPARepository pasteboxJPARepository;
@Test
void testFindAll(){
LocalDateTime now = LocalDateTime.now();
LocalDateTime expTime = now.plusSeconds(45);
LocalDateTime expTime1 = now.plusSeconds(40);
LocalDateTime expTime2 = now.plusSeconds(35);
PasteboxEntity entity = new PasteboxEntity();
entity.setId(0L);
entity.setHash("hash");
entity.setData("Here's my text #1.");
entity.setLifeTime(expTime);
entity.setPublic(true);
PasteboxEntity entity1 = new PasteboxEntity();
entity.setId(1L);
entity.setHash("hash1");
entity.setData("Here's my text #2.");
entity.setLifeTime(expTime1);
entity.setPublic(true);
PasteboxEntity entity2 = new PasteboxEntity();
entity.setId(2L);
entity.setHash("hash2");
entity.setData("Here's my text #3.");
entity.setLifeTime(expTime2);
entity.setPublic(true);
List<PasteboxEntity> entities = new ArrayList<>();
entities.add(entity);
entities.add(entity1);
entities.add(entity2);
when(pasteboxJPARepository.findAll()).thenReturn(entities);
assertEquals(3, pasteboxService.testMethodEntity().size());
}
}
物體類:
@Data
@Entity
@Table(name = "paste_box_entities")
public class PasteboxEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "data")
private String data;
@Column(name = "hash")
private String hash;
@Column(name = "lifetime")
private LocalDateTime lifeTime;
@Column(name = "ispublic")
private boolean isPublic;
}
服務類(這里我寫了所有元素的輸出,看看那里發生了什么)
@Service
@RequiredArgsConstructor
public class PasteboxServiceImpl implements PasteboxService {
private final PasteboxJPARepository pasteboxJPARepository;
public List<PasteboxEntity> testMethodEntity(){
for(PasteboxEntity e : pasteboxJPARepository.findAll())
System.out.println(e);
return pasteboxJPARepository.findAll();
}
}
存盤庫:
@Repository
public interface PasteboxJPARepository extends JpaRepository<PasteboxEntity, Long> {
PasteboxEntity findByHash(String hash);
List<PasteboxEntity> findAll();
}
在控制臺中,我們可以看到,只有第一個元素不為空,盡管我已經初始化了每個元素。

我試圖在互聯網上找到相同的,但似乎沒什么,所以我來了。
uj5u.com熱心網友回復:
您只設定 的欄位entity,而不是entity1和entity2在您的測驗中......
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534301.html
標籤:爪哇列表单元测试模仿者
