所以我有一個功能。我想測驗一下。它需要一個結構作為引數。并且該結構實作了一些特征。這個 trait 有一個長期運行的 io 方法。我不希望這個 io 方法實際去獲取資料,我想模擬這個 io 方法并回傳結果。我對如何做到這一點有點迷茫。這是我的嘗試(不作業)
struct TestStruct {
a: u32,
b: u32,
}
pub trait TestTrait {
fn some_long_running_io_method(&self) -> u32 {
156
}
}
fn important_func(a: TestStruct) {
println!("a: {}", a.some_long_running_io_method());
}
impl TestTrait for TestStruct {
fn some_long_running_io_method(&self) -> u32 {
self.a self.b
}
}
#[cfg(test)]
mod tests {
use super::*;
use mockall::predicate::*;
use mockall::*;
#[cfg(test)]
mock! {
pub TestStruct {}
impl TestTrait for TestStruct {
fn some_long_running_io_method(&self) -> u32;
}
}
#[test]
fn test_important_func() {
let mut mock = MockTestStruct::new();
mock.expect_some_long_running_io_method()
.returning(|| 1);
important_func(mock);
}
}
我顯然得到了這個錯誤:
error[E0308]: mismatched types
--> src/test.rs:35:24
|
35 | important_func(mock);
| -------------- ^^^^ expected struct `TestStruct`, found struct `MockTestStruct`
| |
| arguments to this function are incorrect
如何實作模擬特征方法?1)一種方法是更改??函式引數,而不是接受具體的結構接受特征。并在 MockTestStruct 上實作這個特性。但是我們有動態調度,它會損害性能。我不希望僅僅為了測驗而降低性能。2) 我也嘗試在測驗所在的地方重新實作 Trait,但 Rust 中不允許有沖突的實作。3) 使函式接受 TestStruct 或 MockTestStruct?可能也不是很好的方法。
你能告訴我慣用的方法是什么嗎?
uj5u.com熱心網友回復:
您可以使您的功能important_func成為通用功能。然后,您可以使用泛型邊界將型別限制為您的 trait 的實作者。
這是您的代碼示例:
struct TestStruct {
a: u32,
b: u32,
}
pub trait TestTrait {
fn some_long_running_io_method(&self) -> u32 {
156
}
}
// important_func can now use any type T which implements TestTrait,
// including your mock implementation!
fn important_func<T: TestTrait>(a: T) {
println!("a: {}", a.some_long_running_io_method());
}
impl TestTrait for TestStruct {
fn some_long_running_io_method(&self) -> u32 {
self.a self.b
}
}
#[cfg(test)]
mod tests {
use super::*;
use mockall::predicate::*;
use mockall::*;
#[cfg(test)]
mock! {
pub TestStruct {}
impl TestTrait for TestStruct {
fn some_long_running_io_method(&self) -> u32;
}
}
#[test]
fn test_important_func() {
let mut mock = MockTestStruct::new();
mock.expect_some_long_running_io_method().returning(|| 1);
important_func(mock);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/525351.html
標籤:测试锈嘲弄
上一篇:保存和加載CNN模型
下一篇:帶有localdateMethodArgumentTypeMismatchException例外的Mockmcv查詢引數
