我正在测试dynamodb存储库。下面是测试的方法
public Book getBook(final String bookId) {
DynamoDbTable<Book> bookTable = getTable();
Key key = Key.builder().partitionValue(bookId)
.build();
return bookTable.getItem(key);
}
private DynamoDbTable<Book> getTable() {
return dynamoDbEnhancedClient.table("Book",
TableSchema.fromBean(Book.class));
}这是测试类
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class BookRepositoryTest {
@Mock
private DynamoDbEnhancedClient dynamoDbEnhancedClient;
@Mock
private DynamoDbTable<Book> dyamoDbTable;
@Mock
private Key key;
@InjectMocks
private BookRepository repository;
private final String BOOK_ID = "123";
private static MockedStatic<TableSchema> tableSchema;
@BeforeAll
public static void init() {
tableSchema = mockStatic(TableSchema.class);
}
@AfterAll
public static void close() {
tableSchema.close();
}
@Test
void testGetBook() {
Book book = HelperMethod.createBook();
tableSchema.when(() -> TableSchema.fromBean(Book.class))
.thenReturn(BeanTableSchema.create(Book.class));
when(dynamoDbEnhancedClient.table("Book",
TableSchema.fromBean(Book.class))).thenReturn(dyamoDbTable);
when(dyamoDbTable.getItem(key)).thenReturn(book);
final var result = repository.getBook(BOOK_ID);
assertEquals(book, result);
}
}这是错误
org.opentest4j.AssertionFailedError:预期:Book(bookId=123,keyCode=testKeyCode,eventTimestampMs=123,value=true)实数:null
发布于 2022-08-16 18:04:45
您从未模仿过dyamoDbTable (它似乎拼写错误),所以它是null。而且,我不明白你为什么要嘲笑TableSchema.fromBean;看起来你可以这么做
when(dynamoDbEnhancedClient.table(anyString(), any())).thenReturn(dyamoDbTable)如果你那样做了,你就不需要mockStatic了。
https://stackoverflow.com/questions/73378219
复制相似问题