在科特林与JUnit5我们可以使用assertFailsWith
在带有 JUnit5 的 Java 中,您可以使用assertThrows
在 Java 中,如果我想将可执行文件的声明与执行本身分开,为了以 Given-Then-When 形式阐明测试,我们可以assertThrows像这样使用 JUnit5 :
@Test
@DisplayName("display() with wrong argument command should fail" )
void displayWithWrongArgument() {
// Given a wrong argument
String arg = "FAKE_ID"
// When we call display() with the wrong argument
Executable exec = () -> sut.display(arg);
// Then it should throw an IllegalArgumentException
assertThrows(IllegalArgumentException.class, exec);
}
Run Code Online (Sandbox Code Playgroud)
在 Kotlin 中,我们可以使用assertFailsWith:
@Test
fun `display() with wrong argument command should fail`() { …Run Code Online (Sandbox Code Playgroud) 在 Mongodb 中我有这个字段:
units: NumberDecimal('1'),
Run Code Online (Sandbox Code Playgroud)
映射到:
Units float64 `json:"units"`
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用以下方式从 Go 读取数据:
var result dbo.Invoice
coll := client.Database("hobbit").Collection("customer")
filter := bson.D{{"_id", code}}
err = coll.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
return model.Customer{}, fmt.Errorf("invoice %s not found", code)
}
return model.Customer{}, fmt.Errorf("reading invoice %s from database: %s", code, err)
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
Error: error un-marshalling invoice F-3945: error decoding key lines.0.units: cannot decode 128-bit decimal into a float32 or float64 type
Run Code Online (Sandbox Code Playgroud)
我尝试使用bsoncodec注册转换:
registryBuilder := bsoncodec.NewRegistryBuilder() …Run Code Online (Sandbox Code Playgroud) 在某些情况下,需要清理或重置测试用例之间的模拟。
将 Kotling 与 JUnit5 和 Mockk 一起使用,第一种方法应该是这样的:
class CreateProductsTests {
@Test
fun `run() with an existing product should throw a CrudException`() {
val productRepository = mockk<ProductRepository>()
val editorService = mockk<EditorService>()
val sut = CreateProductServiceImpl(productRepository, editorService)
// Given an editor that return a JSON
val product = completeTestProduct()
every { editorService.edit("Create new Product", product) } returns product
// And the product does exist in the database
every { productRepository.findById(product.id) } returns Optional.of(product)
// When we call createProduct()"
// Then should …Run Code Online (Sandbox Code Playgroud)