我正在尝试为以下方法编写测试类
public class CustomServiceImpl implements CustomService {
@Value("#{myProp['custom.url']}")
private String url;
@Autowire
private DataService dataService;
Run Code Online (Sandbox Code Playgroud)
我在类中的一个方法中使用了注入的url值.为了测试这个,我写了一个junit类
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public CustomServiceTest{
private CustomService customService;
@Mock
private DataService dataService;
@Before
public void setup() {
customService = new CustomServiceImpl();
Setter.set(customService, "dataService", dataService);
}
...
}
public class Setter {
public static void set(Object obj, String fieldName, Object value) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
}
}
Run Code Online (Sandbox Code Playgroud)
在applicationContext-test.xml中我正在使用加载属性文件
<util:properties id="myProp" location="myProp.properties"/>
Run Code Online (Sandbox Code Playgroud)
但是在运行测试时,不会在CustomService中加载url值.我想知道是否有办法完成这项工作.
谢谢
我有一个相当复杂的测试用例我试图将以下verify()添加到:
verify(userService).getUserById(anyLong()).setPasswordChangeRequired(eq(Boolean.TRUE));
Run Code Online (Sandbox Code Playgroud)
这失败了,出现此错误:
org.mockito.exceptions.verification.TooManyActualInvocations:
userService.getUserById(<any>);
Wanted 1 time:
-> at test.controllers.AuthenticationControllerMockTest.testLookupsExceeded(AuthenticationControllerMockTest.java:404)
But was 4 times. Undesired invocation:
Run Code Online (Sandbox Code Playgroud)
所以我改成了这个:
verify(userService, atLeastOnce()).getUserById(anyLong()).setPasswordChangeRequired(eq(Boolean.TRUE));
Run Code Online (Sandbox Code Playgroud)
现在它失败了:
java.lang.NullPointerException
at test.controllers.AuthenticationControllerMockTest.testLookupsExceeded(AuthenticationControllerMockTest.java:404)
Run Code Online (Sandbox Code Playgroud)
因为这返回null:
verify(userService, atLeastOnce()).getUserById(anyLong())
Run Code Online (Sandbox Code Playgroud)
这看起来令人费解 - 如果我使用默认值(仅一次调用),它会失败,因为它被多次调用,但是如果我告诉它多次调用都没问题,它就会失败,因为它无法找到任何调用!
有人能帮忙吗?
我不确定如何模拟枚举单例类.
public enum SingletonObject{
INSTANCE;
private int num;
protected setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
Run Code Online (Sandbox Code Playgroud)
我想在上面的例子中存根getNum(),但我无法弄清楚如何模拟实际的SingletonObject类.我认为使用Powermock准备测试会有所帮助,因为枚举本身就是最终的.
//... rest of test code
@Test
public void test() {
PowerMockito.mock(SingletonObject.class);
when(SingletonObject.INSTANCE.getNum()).thenReturn(1); //does not work
}
Run Code Online (Sandbox Code Playgroud)
这是使用PowerMockMockito 1.4.10和Mockito 1.8.5.
默认情况下,Hamcrest所需的版本为:
Hamcrest 1.1和1.3之间没有重要的API变化.目前我的测试用例试图用Hamcrest 1.1运行JUnit 4.11,但我有理由相信这是一个坏主意.出于类似的原因,我怀疑尝试将Mockito-core 1.9.5与Hamcrest 1.3一起使用也是一个坏主意.
该怎么办?
更新2015-06-12: Mockito 1.10.19和2.0.13-beta仍然使用Hamcrest 1.1
我正在尝试模拟Apache HttpClient接口,以便模拟下面提到的一个方法来返回一个存根的JSON对象作为响应.
HttpResponse response = defaultHttpClient.execute(postRequest);
Run Code Online (Sandbox Code Playgroud)
有人可以通过一些示例代码建议如何实现这一目标吗?非常感谢您的帮助.
谢谢
我正在编写一个selenium测试并使用mockito验证服务器行为.具体来说,当单击一个按钮时,我想确保页面控制器调用我所嘲笑的依赖项上的特定方法.
因为它是一个selenium测试,我需要等待在另一个线程中调用mock,所以我使用mockito timeout.
verify(myMock, timeout(5000).times(1)).myMethod("expectedArg");
Run Code Online (Sandbox Code Playgroud)
我遇到的麻烦是myMethod被多次调用...而不是等待与预期参数匹配的调用,超时只等待第一次调用.如果我使用Thread.sleep(50000)而不是超时(50000),它会按预期工作......但这很脏,所以我希望避免它.
如何使用预期输入等待myMethod?
是否可以在使用非预定义参数调用模拟时抛出异常?有Answers.RETURNS_SMART_NULLS,但它并不是我真正需要的东西,因为它不起作用,如果null是合法的返回值,这不会导致NullPointerException,而是后来的错误.
编辑:一些背景.因此,在定义模拟时,在Mockito中,您可以为每个调用指定返回值,如下所示:
when(myMock.someMethod(arg1, arg2)).thenReturn(returnValue);
Run Code Online (Sandbox Code Playgroud)
当myMock.someMethod使用参数调用时,我没有在测试中给出返回值,它只返回null.我想将它配置为立即崩溃并告诉我,我忘了为某些参数组合定义返回值.
编辑2:有人建议提供一个defaultAnswer在调用时抛出异常的自定义.不幸的是,这不起作用.answer()即使存在模拟,也会调用默认答案的方法.这是一个示例:
public class Test {
public static class Adder {
public int add(int a, int b) {
return a + b;
}
}
public static final Answer<Object> THROW_ON_UNDEFINED_ARGS = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
throw new IllegalArgumentException(
String.format("Calling a mock with undefined arguments: %s %s",
invocation.getMethod(),
Arrays.toString(invocation.getArguments())));
}
};
public static void main(String[] args) { …Run Code Online (Sandbox Code Playgroud) 我有一个图像加载器类,我需要在其中测试一些静态方法.由于Mockito不支持静态方法,我改用Power Mockito.但我正在测试的静态方法有一个方法调用
Base64.encodeToString(byteArray, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)
为了模拟这个,我使用如下的mockStatic方法和@PrepareForTest注释.
PowerMockito.mockStatic(Base64.class);
Run Code Online (Sandbox Code Playgroud)
但Android工作室正在回复我仍然给我一个错误,如下所示.
org.powermock.api.mockito.ClassNotPreparedException:类android.util.Base64未准备好进行测试.要准备此类,请将类添加到"@PrepareForTest"注释中.
以下是我的完整代码.
要测试的代码:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.widget.ImageView;
public static String convertBitmapToBase64(Bitmap imageBitmap, boolean withCompression) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 120, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
Run Code Online (Sandbox Code Playgroud)
测试类代码
import android.graphics.Bitmap;
import android.util.Base64;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.testng.annotations.Test;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class ImageLoaderTest {
@Test
public void testConvertBitmap(){
byte[] array = new byte[20];
PowerMockito.mockStatic(Base64.class);
PowerMockito.when(Base64.encodeToString(array, …Run Code Online (Sandbox Code Playgroud) 为了测试在Spring启动应用程序的组件/豆,春天启动文档的测试部分提供了很多的信息和多种方式:
@Test,@SpringBootTest,@WebMvcTest,@DataJpaTest以及仍有许多其他的方式.
为什么提供这么多方法?如何决定赞成的方式?
我应该考虑的集成测试和春天开机测试注释,比如我的注解测试类@SpringBootTest,@WebMvcTest,@DataJpaTest ?
PS:我创建了这个问题,因为我注意到许多开发人员(甚至经验丰富的人)都没有得到使用注释而不是另一个注释的后果.
据我了解,沉默StrictStubbinglenient引发的异常。基于此,不应该使用,也许只是在执行 TDD 时暂时使用,因为严格的存根异常通常意味着您的代码要么是错误的,测试设计得很糟糕,要么您添加了不必要的行。lenient
lenient是否存在实际需要或对测试有用的实际场景?
mockito ×10
java ×8
junit ×3
unit-testing ×3
android ×2
powermock ×2
asynchronous ×1
dependencies ×1
enums ×1
hamcrest ×1
mocking ×1
properties ×1
selenium ×1
singleton ×1
spring ×1
spring-boot ×1
spring-mvc ×1
testing ×1