我想能够让Mockito在调用给定的void方法时执行自定义操作.
说我有以下代码:
@Autowired
private ProfileService profileService;
@Autowired
private ProfileDao profileDao;
private List<Profile> profiles;
@Before
public void setup() {
Mockito.when(profileDao.findAll()).thenReturn(profiles);
Mockito.when(profileDao.persist(any(Profile.class))).thenAddProfileToAboveList...
}
@Configuration
public static class testConfiguration {
@Bean
public ProfileDao ProfileDao() {
return mock(ProfileDao.class);
}
}
Run Code Online (Sandbox Code Playgroud)
假设我想将配置文件实例添加到配置文件列表中.Mockito能做到吗?如果是这样的话?
我已经阅读了很多关于如何模拟Spring的bean及其自动化字段的文章.但是我无法找到有关自动装配的bean列表的信息.
具体问题
我有一个叫做的课FormValidatorManager.这个类循环遍历几个实现的验证器IFormValidator.
@Component
public class FormValidatorManager implements IValidatorManager {
@Autowired
private List<IFormValidator> validators;
@Override
public final IFieldError validate(ColumnDTO columnToValidate, String sentValue) {
String loweredColName = columnToValidate.getName().toLowerCase();
IFieldError errorField = new FieldError(loweredColName);
for (IEsmFormValidator validator : validators) {
List<String> errrorsFound = validator.validate(columnToValidate, sentValue);
//les erreurs ne doivent pas être cumulées.
if(CollectionUtils.isNotEmpty(errrorsFound)){
errorField.addErrors(errrorsFound);
break;
}
}
return errorField;
}
}
Run Code Online (Sandbox Code Playgroud)
我想测试这门课.但我找不到嘲弄validators财产的方法.
我试过的
既然IFormValidators是单身人士,我试图模仿这些豆类的几个实例,希望它们能够被反映出来FormValidatorManager.validators但却没有成功.
然后,我尝试创建一个IFormValidators注释为 的列表@Mock.通过List手动启动,我希望 …
我是Mockito和jUnit的新手,我尝试学习正确的TDD方法.我需要一些例子,以便我可以使用mockito编写单元测试
以下是我的控制器类,它上传文件并对此文件输入执行一些操作.
@Controller
@RequestMapping("/registration")
public class RegistrationController {
@Autowired
private RegistrationService RegistrationService;
@Value("#{Properties['uploadfile.location']}")
private String uploadFileLocation;
public RegistrationController() {
}
@RequestMapping(method = RequestMethod.GET)
public String getUploadForm(Model model) {
model.addAttribute(new Registration());
return "is/Registration";
}
@RequestMapping(method = RequestMethod.POST)
public String create(Registration registration, BindingResult result,ModelMap model)
throws NumberFormatException, Exception {
File uploadedFile = uploadFile(registration);
List<Registration> userDetails = new ArrayList<Registration>();
processUploadedFile(uploadedFile,userDetails);
model.addAttribute("userDetails", userDetails);
return "registration";
}
private File uploadFile(Registration registration) {
Date dt = new Date();
SimpleDateFormat format = new SimpleDateFormat("MM_dd_yyyy_HH_mm_ss");
File uploadedFile = …Run Code Online (Sandbox Code Playgroud) 我正在使用Mockito进行JUnit测试.所以从我想要测试的代码中使用给定的A类:
class A{
public A(){}
public final String a(String x){
return "A.a: " + x;
}
}
Run Code Online (Sandbox Code Playgroud)
我想用另一个方法调用替换方法调用Aa与相同的参数和相同类型的返回值.正如您所看到的,不可能通过扩展类来覆盖方法a,因为它是最终的.所以我现在拥有的另一个B类方法是Bb:
class B{
public B(){}
public String b(String x){
return "B.b: " + x;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想确保每次从代码中调用Aa时,都会使用Bb的返回值.是否有可能通过Mockito(类似的东西Mockito.when(A.a(x)).thenReturn(B.b(x));)实现这一点,但使用相同的参数x,而不知道x的值?
任何帮助将不胜感激,谢谢你提前!
我正在研究一个Java项目想要为DTO中的.equals方法编写单元测试.在.equals方法中,有一个.getClass()方法被两个被测对象调用.我想嘲笑这个,但我不知道它想要什么类型的对象.我试过了,
when(mockRoomInv.getClass()).thenReturn(RoomInv.class);
但肯定是没有做任何事情.getClass的返回类型是什么,我该如何操作它?
我正在研究一个继承的代码.我写了一个应该捕获NullPointerException的测试(因为它试图从null对象调用一个方法)
@Test(expected=NullPointerException.class)
public void checkXRequirement_NullProduct_AddAction_ShouldThrowNullPointerException() throws CustomException {
Site site = mock(Site.class);
Product product = null;
when(BasketHelper.getAction(request)).thenReturn(0);
when(BasketHelper.getActionProduct(site, request)).thenReturn(product);
BasketHelper.requiresX(request, site);
}
Run Code Online (Sandbox Code Playgroud)
相关方法和变量:
public static final int ACTION_ADD = 0;
public static final int ACTION_DELETE = 1;
protected static int getAction(HttpServletRequest a_request) {
String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT);
String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT);
if (sBuyProduct != null) iAction = ACTION_ADD;
else (sDelProduct != null) iAction = ACTION_DELETE;
return iBasketAction
}
protected static Product getActionProduct(Site a_site, HttpServletRequest a_request) {
String sBuyProduct = a_request.getParameter(ATTRIBUTE_NAME_BUY_PRODUCT); …Run Code Online (Sandbox Code Playgroud) 我有以下课程:
public class MyClass {
private Apple apple;
public void myMethod() {
apple = AppleFactory.createInstance(someStringVariable);
....
....
....
}
}
Run Code Online (Sandbox Code Playgroud)
和测试类:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@InjectMocks
MyClass myClass;
@Test
public void myMethod(){
...
...
...
}
}
Run Code Online (Sandbox Code Playgroud)
我如何在MyClass中注入Apple实例作为模拟?
假设我有一个有两种方法的类,我不关心哪种被称为...
public class Foo {
public String getProperty(String key) {
return getProperty(key, null);
}
public String getProperty(String key, String defaultValue) {
//...
}
}
Run Code Online (Sandbox Code Playgroud)
以下(来自另一个类,仍然在我的应用程序中)应该通过我的测试:
public void thisShouldPass(String key) {
// ...
String theValue = foo.getProperty(key, "blah");
// ...
}
public void thisShouldAlsoPass(String key) {
// ...
String theValue = foo.getProperty(key);
if (theValue == null) {
theValue = "blah";
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我不在乎调用哪个,我只想要调用两个变体中的一个.
在Mockito,我通常可以这样做:
Mockito.verify(foo, atLeastOnce()).getProperty(anyString());
Run Code Online (Sandbox Code Playgroud)
要么:
Mockito.verify(foo, atLeastOnce()).getProperty(anyString(), anyString());
Run Code Online (Sandbox Code Playgroud)
是否有一种本地方式可以说"验证其中一个或另一个至少发生过一次"?
或者我必须做一些粗暴的事情:
try {
Mockito.verify(foo, atLeastOnce()).getProperty(anyString());
} …Run Code Online (Sandbox Code Playgroud) 我正在努力让一些罐头网络响应.我对实际请求有json响应,并且我有Retrofit接口来序列化响应.试图设置它我感到非常沮丧.我该怎么办?看来我的选择是,1)使用MockWebServer()2)使用RequestInterceptor().
在尝试使用1或2时,我不能在我的生活中实例化OkHttpClient()而不会失败,基本上这会把我试图立即死亡的每一件事.我得到一个java.lang.AssertionError,因为当OkHttpClient无法找到TLS算法时会抛出它.
if (builder.sslSocketFactory != null || !isTLS) {
this.sslSocketFactory = builder.sslSocketFactory;
} else {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
this.sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
**throw new AssertionError(); // The system has no TLS. Just give up.**
}
}
Run Code Online (Sandbox Code Playgroud)
我试图使用unMock在android.jar中保留"javax.net.ssl"类,但这并没有解决错误.
unMock {
// URI to download the android-all.jar from. e.g. https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/
downloadFrom 'https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/4.3_r2-robolectric-0/android-all-4.3_r2-robolectric-0.jar'
keep "android.util.Log"
keep "javax.net.ssl"
}
Run Code Online (Sandbox Code Playgroud)
所以基本上,我已经遇到过如何通过改造2模拟网络请求的各种示例,但我无法克服这个障碍,而且我感觉很失败.我还没有看到其他人遇到过这个问题,而且我很困惑于每个人如何在所有测试中轻松实例化新的OkHttpClients.
以下是我正在使用的相关依赖项.
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-all:1.10.19'
testCompile 'org.powermock:powermock-mockito-release-full:1.6.4'
testCompile 'org.powermock:powermock-module-junit4:1.6.4'
testCompile 'org.easymock:easymock:3.4'
testCompile 'org.powermock:powermock-api-easymock:1.6.4'
testCompile …Run Code Online (Sandbox Code Playgroud) 在Android Studio中,当我调试检测测试时,测试不会在任何断点上停止.调试单元测试工作.我有一个简单的检测测试,只检查是否显示用户名edittext:
@RunWith(AndroidJUnit4.class)
public class LogonActivityTest {
@Rule
public ActivityTestRule<LogOnActivity> mActivityRule = new ActivityTestRule<>(LogOnActivity.class, true, false);
@Before
public void setUp() throws Exception {
mActivityRule.launchActivity(new Intent()); // breakpoint here
}
@Test
public void testSimple() throws Exception {
onView(withId(R.id.act_logon_et_username)).check(matches(isDisplayed())); // breakpoint here
}
}
Run Code Online (Sandbox Code Playgroud)
在build.gradle我已正确设置
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
Run Code Online (Sandbox Code Playgroud)
如何调试检测测试?我正在使用Espresso,Mockito和Dagger 2.
android mockito android-testing android-studio android-espresso