Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JUnit断言强制执行一行_Java_Unit Testing_Junit_Mockito - Fatal编程技术网

Java JUnit断言强制执行一行

Java JUnit断言强制执行一行,java,unit-testing,junit,mockito,Java,Unit Testing,Junit,Mockito,是否有任何junit断言,我可以用它强制执行一行 例如: doAnswer(new Answer<Void>() { @SuppressWarnings("unchecked") @Override public Void answer(final InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments();

是否有任何junit断言,我可以用它强制执行一行

例如:

doAnswer(new Answer<Void>() {
    @SuppressWarnings("unchecked")
    @Override
    public Void answer(final InvocationOnMock invocation) throws Throwable {
        Object[] arguments = invocation.getArguments();
        Map<String, String> fieldMapActual = (Map<String, String>) arguments[0];
        assertEquals(fieldMap, fieldMapActual);

        **assertFailIfThisLineIsNotExecuted();**

        return null;
    }
}).when(x).myMethod(xxx);

如果我有机会编写类似AssertFailyIfthislineisnotexecuted in the answer方法的东西,我就不必定义额外的验证。那么,是否有任何junit断言,我可以用它强制执行一行?与fail()相反,不立即将方法定义为“successful”。

如果要确保执行测试的某一行,请使用布尔标志:

 final boolean[] wasExecuted = { false };

 ...
     wasExecuted[0] = true;
 ...

 assertTrue("Some code wasn't executed", wasExecuted);
但我的直觉是你在试图解决一个不同的问题

verify
显示“必须调用此方法”。不管你是否嘲笑一个答案。这就是你应该使用的方法

只有在由于某种原因无法创建模拟时,我才使用我的标志方法。如果发生这种情况,我将在测试代码中扩展被测试的类并添加标志

与verify相比,标志的优势在于,标志记录了我希望代码出现的位置(您可以让IDE搜索使用标志的所有位置)<代码>验证()在失败时不容易找到

verify(x).myMethod(xxx)应该是您想要的。它也表达了意图


assertFailIfThisLineIsNotExecuted()
也将是一行代码(那么它如何比
verify
?“更好”),JUnit不支持它,您必须编写代码才能获得良好的错误消息,等等。

如果您验证
answer
的处理结果,您就会知道它。为什么你不能测试它的行为?myMethod是无效的,doAnswer是最常用的。你不应该嘲笑你正在测试的单元。如果您正在测试myMethod是否在特定情况下被调用(这就是您使用“AssertifyThislineisNotExecuted”所说的然后你真的在测试你的模拟的行为。换句话说,至少在我看来,你永远不应该在
doAnswer
中有一个
assert*
,有些情况下,它是100%有意义的。应该这样做。例如:用例2I会投票+1支持
,但我的直觉是,你正在试图解决一个不同的问题。
使用标志很好,但你是对的..验证应该是正确的方法。当我都想要模拟和验证时,我感到不舒服,因为方法参数必须定义两次。我只希望在定义模拟时添加一个额外的参数,无论这个调用是可选的还是强制性的;因此我不必编写验证。我们不幸的是,我们有4-5个参数的方法,甚至当我们不得不使用ArgumentCaptor等时。你可能会猜到验证本身可能由3行或其他内容组成。将
ArgumentCaptor
移动到helper方法中,这样你就可以编写
(foo(…)、bar(…)、baz(…)
 final boolean[] wasExecuted = { false };

 ...
     wasExecuted[0] = true;
 ...

 assertTrue("Some code wasn't executed", wasExecuted);