最近我切换到了Mockito框架并且对它非常满意(另见blog-post).从EasyMock到Mockito的转换非常简单,我设法使测试兼容(即测试用例表现相同).
你是否看到真正的理由或枪战标准更喜欢EasyMock而不是Mockito?到目前为止我使用的代码库不能,但我对你的观点感兴趣.
我在Mockito有这个:
when(mockedMergeContext.createNewEntityOfType(IService.class)).thenReturn(new ServiceMock());
Run Code Online (Sandbox Code Playgroud)
该createNewEntityOfType方法应始终返回一个新ServiceMock实例,但它返回两次相同的引用.
为什么该thenReturn方法不返回新的ServiceMock?
我有一个DummyResource类和一个DummyTarget文件,以及一个测试类TestDummyResource,如下所示,但是DummyResource dr = mock(DummyResource.class)当我在普通类中调用构造函数时,模拟对象才起作用,当它在匿名类中调用时,它调用实际的构造函数而不是使用被模拟的对象.
版本:
powermock 1.4.12 mockito 1.9.0 junit 4.8.2
DummyTarget.java:
import java.io.IOException;
import java.io.OutputStream;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
public class DummyTarget {
public StreamingOutput testMocking() {
return new StreamingOutput() {
@Override
public void write(OutputStream arg0) throws IOException, WebApplicationException {
new DummyResource();
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
DummyResource.java:
package com.smin.dummy;
public class DummyResource {
public DummyResource() {
System.out.println("mock failure");
}
}
Run Code Online (Sandbox Code Playgroud)
TestDummyResource.java:
package com.smin.dummy;
import static org.mockito.Mockito.mock;
import java.io.IOException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Before;
import org.junit.Test;
import …Run Code Online (Sandbox Code Playgroud) 我问,因为我试图使用一个模拟框架(Mockito),它不允许你模拟静态方法.调查一下我发现有不少博客文章说你应该尽可能少的静态方法,但是我很难理解为什么.特别是为什么不修改全局状态的方法基本上是辅助方法.例如,我有一个名为ApiCaller有几个静态方法的类.静态方法的一个目的是执行HTTP调用,处理我们的服务器可能返回的任何自定义问题(例如用户未登录)并返回响应.为了简化,例如:
public class ApiCaller {
...
public static String makeHttpCall(Url url) {
// Performs logic to retrieve response and deal with custom server errors
...
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
要使用这一切,我所要做的就是调用ApiCaller.makeHttpCall(url)
Now我可以很容易地将它变为非静态方法,如:
public class ApiCaller {
...
public String makeHttpCall(Url url) {
// Performs logic to retrieve response and deal with custom server errors
...
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用此方法调用,new ApiCaller().makeHttpCall()但这似乎是额外的开销.任何人都可以解释为什么这是坏的,如果有一个更好的解决方案使方法非静态(除了删除关键字),以便我可以使用模拟框架存根这些方法?
谢谢!
我尝试为我的JSF应用程序和我使用mockito的模拟实现一些测试.(我也用春天)
@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImplTest {
private GeneralConfigService generalConfigService;
@Mock
private GeneralConfigDAO generalConfigDAO;
@Mock
private GeneralConfig gen;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
generalConfigService = new GeneralConfigService();
ReflectionTestUtils.setField(generalConfigService, "generalConfigDAO", generalConfigDAO);
}
@Test
public void testAddGeneralConfigCallDAOSuccess() throws DAOException, EntityNullException, IllegalEntityArgumentException, ParseException, EntityPersistException {
gen = createGeneralConfigs("label", "value");
generalConfigService.setInstance(gen);
generalConfigService.persist();
log.info(generalConfigService.getInstance().toString());
}
}
Run Code Online (Sandbox Code Playgroud)
测试成功,但是当我想用getInstance方法检索实例时.我之前设置的所有参数(通过之前的构造函数)都为null.我是模拟对象的新手,所以这种行为是正常的,还是我的代码中有错误?
我是mockito的忠实粉丝,不幸的是,对于我使用Java 8的一个项目,它失败了...
场景:
public final class MockTest
{
@Test
public void testDefaultMethodsWithMocks()
{
final Foo foo = mock(Foo.class);
//when(foo.bar()).thenCallRealMethod();
assertThat(foo.bar()).isEqualTo(42);
}
@FunctionalInterface
private interface Foo
{
int foo();
default int bar()
{
return 42;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,测试失败并foo.bar()返回0.
当我取消注释该when()行时,我得到一个堆栈跟踪...
java.lang.NoSuchMethodError: java.lang.Object.bar()I
at com.github.fge.lambdas.MockTest.testDefaultMethodsWithMocks(MockTest.java:18)
Run Code Online (Sandbox Code Playgroud)
这是maven上最新的稳定版本; 谷歌搜索周围没有告诉我关于Java 8中这个新功能的模拟状态...
你能否以其他方式使其工作,而不是实现接口和spy()它们(这是有效的)?
我正在使用Mockito 1.9.5.如何模拟受保护方法返回的内容?我有这种受保护的方法......
protected JSONObject myMethod(final String param1, final String param2)
{
…
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在JUnit中执行此操作时:
final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);
final String pararm1 = “param1”;
Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);
Run Code Online (Sandbox Code Playgroud)
在最后一行,我得到一个编译错误"方法'myMethod'不可见."我如何使用Mockito来模拟受保护的方法?如果这是答案,我愿意升级我的版本.
我刚刚阅读了Android中的单元仪表测试,我想知道如何在没有任何SharedPreferencesHelper类的情况下模拟SharedPreferences,就像这里一样
我的代码是:
public class Auth {
private static SharedPreferences loggedUserData = null;
public static String getValidToken(Context context)
{
initLoggedUserPreferences(context);
String token = loggedUserData.getString(Constants.USER_TOKEN,null);
return token;
}
public static String getLoggedUser(Context context)
{
initLoggedUserPreferences(context);
String user = loggedUserData.getString(Constants.LOGGED_USERNAME,null);
return user;
}
public static void setUserCredentials(Context context, String username, String token)
{
initLoggedUserPreferences(context);
loggedUserData.edit().putString(Constants.LOGGED_USERNAME, username).commit();
loggedUserData.edit().putString(Constants.USER_TOKEN,token).commit();
}
public static HashMap<String, String> setHeaders(String username, String password)
{
HashMap<String, String> headers = new HashMap<String, String>();
String auth = username + ":" + …Run Code Online (Sandbox Code Playgroud) 我正在使用@RunWith(MockitoJUnitRunner.class)mockito进行junit测试.但现在我正在使用spring boot app并尝试使用@RunWith(SpringRunner.class).使用是否比使用@RunWith(SpringRunner.class)有任何优势@RunWith(MockitoJUnitRunner.class)?我仍然可以使用功能一样@Injectmock,@Mock,@Spy与@RunWith(SpringRunner.class)
想象一下以下代码:
List list = .....
List spy = spy(list);
doThrow(new NullpointerException()).when(spy).get(0);
Run Code Online (Sandbox Code Playgroud)
doThrow(....)执行list.get(0)- 这根本没有意义.我想定义模拟行为,而不是在这里调用方法.....我错过了什么?
编辑:列表由CGLIB装饰.当我删除CGLIB代理时,Mockito按预期工作.任何想法在使用CGLIB代理时如何解决这样的问题?