Domanda

If I have a struct like:

struct Foo {
  bar: int,
  baz: bool
}

and a default constructor like:

impl Foo {
  fn default() -> ~Foo {
    Foo{bar: 0, baz: false}
  }
}

I'd want a unit test for my constructor:

#[test]
fn test_foo_default() {
  let foo1 = Foo::default();
  let foo2 = ~Foo{bar: 0, baz: false};
  // What to put here to compare them?
}

How do I easiest compare the two structs to make sure they are the same with regards to content, type and ownership?

È stato utile?

Soluzione

Have the compiler derive the Eq trait for Foo (if possible), and then check for equality with the assert_eq! macro. The macro also requires Show to be implemented for some reason, so let's derive it as well. Your original default() function doesn't actually compile because it attempts to return a Foo where a ~Foo was promised. Foo and ~Foo are actually different types, but you can dereference a ~Foo and compare that.

You may also be interested in the Default trait.

#[deriving(Eq,Show)]
struct Foo {
    bar: int,
    baz: bool
}

impl Foo {
    fn default() -> ~Foo {
        ~Foo{bar: 0, baz: false}
    }
}

#[test]
fn test_foo_default() {
    let foo1 = Foo::default();
    let foo2 = ~Foo{bar: 0, baz: false};
    assert_eq!(foo1,foo2);
}

#[test]
fn test_foo_deref() {
    let foo1 = Foo::default();
    let foo2 = Foo{bar: 0, baz: false};
    assert_eq!(*foo1,foo2);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top