我正在尝试为一个不带任何参数的方法编写单元测试,该方法内部使用一个mongoTemplate来使用条件进行查询。让我先发布实体类
@Data
@Builder
@Getter
@Setter
@NoAgrsConstructor
@EqualAndHashCode
public class MyInventory{
@Id
private String id;
@Field("it_key")
@JsonProperty("it_key")
private String it_key;
............在我的服务类中,它使用以下方法检索数据
public List<MyInentory> getAllData(){
Query query = new Query();
//some criteria here
query.addCriteria(criteria);
List<MyInventory> listOfInventory = mongoTemplate.find(query,MyInventory.class);
return listOfInventory;
}我正在尝试为它编写单元测试。
@RunWith(SpringRunner.class)
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness=Strictness.LENIENT)
@SpringBootTest(classes={MongoTemplate.class}
@ActiveProfiles("mock")
public class MyInventoryServiceTest{
@MockBean
private MongoTemplate mongoTemplate;
@Test
public void testGetAllData(){
mockMyInentoryList.add(MyInventory.builder()
.id("614a4d70cghyt86")
.it_key("DESS")
//.........setting the data here
.build()
);
List<MyInventory> expected = new ArrayList<>();
Inventory inv = Mockito.mock(MyInventory.class);
expected.add(inv);
when(this.mongoTemplate.find(any(Query.class),eq(MyInventory.class)))
.thenReturn(mockMyInentoryList);
Assert.asserEquals(mockMyInentoryList,expected);我得到的错误是
java.lang.AssertionError
Expected:[MyInventory(id=614a4d70cghyt86,it_key=DESS........]
Actual: [Mock for MyInventory, hashcode: 1252142274]发布于 2021-10-06 01:56:38
您应该在测试中调用getAllData(),并验证返回的结果是否与模拟的Mongo模板返回的结果匹配:
测试将如下所示:
@Test
public void testGetAllData() {
MyInventoryService myInventoryService = new MyInventoryService(mongoTemplate);
List<MyInventory> mockMyInventoryList = new ArrayList<>();
mockMyInventoryList.add(MyInventory.builder()
.id("614a4d70cghyt86")
.it_key("DESS")
//.........setting the data here
.build()
);
when(this.mongoTemplate.find(any(Query.class), eq(MyInventory.class)))
.thenReturn(mockMyInventoryList);
Assert.assertEquals(mockMyInventoryList, myInventoryService.getAllData());
}https://stackoverflow.com/questions/69455220
复制相似问题