JMockit 返回集合
我有以下代码:
public void someMethod() {
Set<Foo> fooSet = bar.getFoos();
for(Foo foo: fooSet) {
foo.doSomething();
}
}
我想使用 JMockit 测试它,但不确定如何返回特定类型和大小的集合。
当尝试将 foo 添加到 foo 集合时,我的代码的以下测试会引发哈希码的空指针异常。
@Test
public void someTestMethod()
{
new Expectations()
{
@Mocked Bar bar;
@Mocked Foo foo;
Set<Foo> foos = new HashSet<Foo>();
foos.add(foo);
bar.getFoos(); returns(foos);
foo.doSomething();
};
new SomeClass().someMethod();
}
这应该怎么做呢?
I have the following code:
public void someMethod() {
Set<Foo> fooSet = bar.getFoos();
for(Foo foo: fooSet) {
foo.doSomething();
}
}
and I want to test this using JMockit but am unsure how to get to return a collection of a certain type and size.
The following test for my code throws a null pointer exception for hashcode when trying to add foo to the set of foos.
@Test
public void someTestMethod()
{
new Expectations()
{
@Mocked Bar bar;
@Mocked Foo foo;
Set<Foo> foos = new HashSet<Foo>();
foos.add(foo);
bar.getFoos(); returns(foos);
foo.doSomething();
};
new SomeClass().someMethod();
}
How should this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不太确定如何回答你的问题,因为我不明白你要测试什么,但我相信你想要这样的东西:
使用这个,JMockit 将模拟对
getFoos
的调用并返回设置foos
。如果您查看我传入的参数,就会发现我正在对 Bar 和 Foo 类进行部分模拟(我只是模拟对 getFoos 和 doSomething 方法的调用)。我还注意到您在new Expectations
块中缺少一组大括号,因此这肯定会给您带来一些问题。您必须记住的另一问题是,如果您在 Setfoos
中放入多个对象,则使用 Expectations 而不是 NonStrictExpectations 会导致错误,因为它只期望对进行一次调用做某事
。如果您创建一个测试用例,其中 foos 包含多个对象,您可以使用 NonStrictExpectations 或使用 minTimes 和 maxTimes 来指定调用计数约束I'm not exactly sure how to answer your question because I don't understand what you are trying to test, but I believe you want something like this:
Using this, JMockit will mock the call to
getFoos
and return the Setfoos
. If you look at the parameters I am passing in, I am doing a partial mock of the Bar and Foo classes (I am only mocking the calls to the getFoos and doSomething method). I also noticed you are missing a set of braces in yournew Expectations
block, so that could definitely cause you some problems. One other issue you have to keep in mind is that using Expectations as opposed to NonStrictExpectations will cause an error if you put more than one object in the Setfoos
because it is only expecting one call todoSomething
. If you make a test case wherefoos
has more than one object in it you could either use NonStrictExpectations or use the minTimes and maxTimes to specify invocation count constraints