[英]JUnit test - asset or verify (or both) on a mock object?
I am playing around writing a JUnit test for some beans I have defined in my code, in order to learn about spring configuration via java annotations. 我正在为我在代码中定义的一些bean编写JUnit测试,以通过java注释了解spring配置。 The test code looks like this: 测试代码如下:
public class FooTest {
@MockBean
private Baz baz; //injected
@MockBean
private Qux qux; //injected
public void testBar() {
Foo foo = new Foo(baz);
Qux reponse = foo.bar();
// verify or assert?
}
}
And the other classes are defined like this: 其他类的定义如下:
@Component
class Foo {
Baz baz;
@Autowired
Foo(Baz baz) {
this.baz = baz
}
Qux bar() {
baz.waldo();
baz.fred();
return baz.newQux();
}
}
@Component
class Baz {
//...
}
As you can see in my JUnit test, I return a Qux
response from the mocked Qux
bean in the FooTest
class. 在JUnit测试中可以看到,我从FooTest
类中的FooTest
Qux
bean返回了Qux
响应。 It got me thinking about testing the bar
method in class Foo
. 这让我开始考虑在Foo
类中测试bar
方法。 I see 3 options here and was wondering what would be considered best practice? 我在这里看到3个选项,并且想知道什么是最佳做法?
response
in test method testBar
on the qux
instance variable in FooTest
. 做在一个的assertEquals response
于测试方法testBar
上qux
在实例变量FooTest
。 verify
on the baz
instance in FooTest
that waldo
and fred
were also called? 上面verify
对FooTest
中的baz
实例进行了verify
,以verify
也调用了waldo
和fred
? Or are these verify calls superfluous, since the baz
is returned, I assume they were called? 还是这些验证调用是多余的,因为返回了baz
,所以我假设它们被调用了? Firstly, you need to define what happens when these statements are executed. 首先,您需要定义执行这些语句时发生的情况。
baz.waldo();
baz.fred();
baz.newQux();
Since baz is a mock. 由于baz是一个模拟。
Secondly you have to do verify to make sure all the methods are called. 其次,您必须进行验证以确保所有方法都被调用。 You can also do assert. 您也可以断言。 But first you need to define what has to be retuened when baz.newQux()
is called. 但是首先,您需要定义在baz.newQux()
时必须修复的内容。 And check the response of foo.bar()
if this is same as what you have defined. 并检查foo.bar()
的响应是否与您定义的相同。
If there is a possibility to do Assert , do it. 如果有可能断言 ,那就去做。 In this case you will check the actual value that method returns after it was invoked. 在这种情况下,您将检查方法被调用后返回的实际值。
Verify only checks that method was called. 仅验证检查该方法是否被调用。 This is more useful when you call some method and you want to check that another method was called inside, but you couldn't do it based on the return object. 当您调用某个方法并且要检查是否在内部调用了另一个方法,但您无法基于返回对象执行此操作时,此功能将更为有用。 In your case you return the whole object, thus, from my point of you, you should be able to use assert. 在您的情况下,您将返回整个对象,因此,从您的角度来看,您应该可以使用assert。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.