2017-07-03 50 views
1

我期待從模擬中調用setAttribute時遇到問題。具有setAttribute的JMock匹配器(字符串,對象)

MyClass { 
    public final void setAttribute(String name, Object value) { 
    // Do Something 
} 

myClass.setAttribute("Key", "Value"); 

在調用setAttribute操作時,String作爲值傳遞。 我有一個名爲mockMyClass的上述類的模擬和我的期望塊我有下面的代碼。

oneOf(mockMyClass).setAttribute(with(equal("Key")), with(equal("Value"))); 

我一直在使用任何也嘗試,只是爲了看看通用的作品,但也給予了同樣的問題。

異常我越來越:

java.lang.IllegalArgumentException: not all parameters were given explicit matchers: either all parameters must be specified by matchers or all must be specified by values, you cannot mix matchers and values

最初我是想沒有任何的匹配,並得到例外:

oneOf(mockMyClass).setAttribute("Key", "Value"); 

org.jmock.api.ExpectationError: unexpected invocation

如何得到這個工作?我打算檢查實際值。

回答

1

化妝方法不是最終

public void setAttribute(String name, Object value) {} 

並使用

oneOf(mockMyClass).setAttribute("Key", "Value"); 

或與匹配任何();

from jmock - ClassImposteriser無法創建最終類或模擬最終方法的模擬。

Mocking Classes with jMock and the ClassImposteriser Because it uses Java's standard reflection capability, the default configuration of the jMock framework can only mock interfaces, not classes. (Actually, we consider that to be a good thing because it encourages the design to focus on communication between objects rather than static classification or data storage). However, the ClassImposteriser extension class uses the CGLIB 2.1 and Objenesis libraries to create mock objects of classes as well as interfaces. This is useful when working with legacy code to tease apart dependencies between tightly coupled classes.

The ClassImposteriser creates mock instances without calling the constructor of the mocked class. So classes with constructors that have arguments or call overideable methods of the object can be safely mocked. However, the ClassImposteriser cannot create mocks of final classes or mock final methods.

If you want to mock final classes or final methods, the JDave library includes an unfinalizer Instrumentation agent that can unfinalise classes before they are loaded by the JVM. They can then be mocked by the ClassImposteriser.