Skip to content

Commit 9bfe21f

Browse files
authored
refactor: Support generic types in test_context macro (#45)
* refactor: Support generic types in test_context macro
1 parent a58e13e commit 9bfe21f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@ impl TestContext for MyContext {
2929
fn test_works(ctx: &mut MyContext) {
3030
assert_eq!(ctx.value, "Hello, World!");
3131
}
32+
33+
struct MyGenericContext<T> {
34+
value: T
35+
}
36+
37+
impl TestContext for MyGenericContext<u32> {
38+
fn setup() -> MyGenericContext<u32> {
39+
MyGenericContext { value: 1 }
40+
}
41+
}
42+
43+
#[test_context(MyGenericContext<u32>)]
44+
#[test]
45+
fn test_generic_type(ctx: &mut MyGenericContext<u32>) {
46+
assert_eq!(ctx.value, 1);
47+
}
3248
```
3349

3450
with generic types, you can use same type with different values

test-context/tests/test.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,45 @@ async fn test_async_skip_teardown(mut _ctx: TeardownPanicContext) {}
170170
#[test_context(TeardownPanicContext, skip_teardown)]
171171
#[test]
172172
fn test_sync_skip_teardown(mut _ctx: TeardownPanicContext) {}
173+
174+
struct GenericContext<T> {
175+
contents: T,
176+
}
177+
178+
impl TestContext for GenericContext<u32> {
179+
fn setup() -> Self {
180+
Self { contents: 1 }
181+
}
182+
}
183+
184+
impl TestContext for GenericContext<String> {
185+
fn setup() -> Self {
186+
Self {
187+
contents: "hello world".to_string(),
188+
}
189+
}
190+
}
191+
192+
impl AsyncTestContext for GenericContext<u64> {
193+
async fn setup() -> Self {
194+
Self { contents: 1 }
195+
}
196+
}
197+
198+
#[test_context(GenericContext<u32>)]
199+
#[test]
200+
fn test_generic_with_u32(ctx: &mut GenericContext<u32>) {
201+
assert_eq!(ctx.contents, 1);
202+
}
203+
204+
#[test_context(GenericContext<String>)]
205+
#[test]
206+
fn test_generic_with_string(ctx: &mut GenericContext<String>) {
207+
assert_eq!(ctx.contents, "hello world");
208+
}
209+
210+
#[test_context(GenericContext<u64>)]
211+
#[tokio::test]
212+
async fn test_async_generic(ctx: &mut GenericContext<u64>) {
213+
assert_eq!(ctx.contents, 1);
214+
}

0 commit comments

Comments
 (0)