我想使用严格的模拟,至少在第一次开发一些针对旧代码的测试时,所以如果我没有专门定义期望,那么在我的模拟上调用的任何方法都会抛出异常.
从我所看到的情况来看,如果我没有定义任何期望,Mockito将只返回null,稍后会在其他地方导致NullPointerException.
有可能吗?如果有,怎么样?
我试图在调用具有可变数量的参数(...Java中的东西)的方法时使用参数匹配器而没有成功.我的代码在下面,我还列出了我尝试使用的所有行来完成这项工作.
import static org.mockito.Mockito.*;
public class MethodTest {
public String tripleDot(String... args) {
String sum = "";
for (String i : args) {
sum += i;
}
System.out.println(sum);
return sum;
}
public static void main(String[] args) {
try{
MethodTest mt = mock(MethodTest.class);
when(mt.tripleDot((String[])anyObject())).thenReturn("Hello world!");
System.out.println(mt.tripleDot(new String[]{"1","2"}));
}
catch (Exception e) {
System.out.println(e.getClass().toString() + ": " + e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果print语句是:
System.out.println(mt.tripleDot(new String[]{"1"}));
Run Code Online (Sandbox Code Playgroud)
要么
System.out.println(mt.tripleDot("1"));
Run Code Online (Sandbox Code Playgroud)
它将打印"Hello world".
但如果print语句是:
System.out.println(mt.tripleDot(new String[]{"1","2"}));
Run Code Online (Sandbox Code Playgroud)
要么
System.out.println(mt.tripleDot("1","2"));
Run Code Online (Sandbox Code Playgroud)
它将打印"null".
我也尝试过调用时的变化,例如anyObject()或者anyString()无效.我不确定Mockito是否可以处理包含可变数量参数的方法调用的参数匹配器.它甚至可能吗?如果是这样,我应该怎么做才能使这项工作?
我正在测试一个在类中调用其他几个void方法的void方法(所有这些方法都在同一个类中).这种方法是这样的......
public void methodToTest() {
methodA();
methodB();
}
void methodA() {
methodA1();
methodA2();
methodA3();
}
Run Code Online (Sandbox Code Playgroud)
我想做的是让methodA()上面什么都不做.也就是说,我想methodA()基本上是这样的:
void methodA() { }
Run Code Online (Sandbox Code Playgroud)
我都试过doThrow(),并doAnswer()于methodA()无济于事.好像那些都被完全忽略了.
我试过的一个例子......
doThrow(new RuntimeException()).when(mockedClass).methodA();
Run Code Online (Sandbox Code Playgroud)
有没有办法只使用Mockito?我不能自由改变被修改的课程.
我想能够让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-test配置内部类(@Configuration)配置组件测试.经过测试的组件有一些我想模拟测试的服务.这些服务是类(没有使用接口)并且@Autowired在其中具有spring注释().Mockito可以很容易地模仿它们,但是,我发现无法禁用弹簧自动装配.
我可以轻松重现的示例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SomeTest.Beans.class)
public class SomeTest {
// configured in component-config.xml, using ThirdPartyService
@Autowired
private TestedBean entryPoint;
@Test
public void test() {
}
@Configuration
@ImportResource("/spring/component-config.xml")
static class Beans {
@Bean
ThirdPartyService createThirdPartyService() {
return mock(ThirdPartyService.class);
}
}
}
public class ThirdPartyService {
@Autowired
Foo bar;
}
public class TestedBean {
@Autowired
private ThirdPartyService service;
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,"TestBean"表示要模拟的服务.我不希望春天注入"酒吧"!@Bean(autowire = NO)没有帮助(事实上,这是默认值).(请保存我从"使用界面!"评论 - 模拟服务可以是第三方,我无法做任何事情.)
UPDATE
Springockito部分解决了这个问题,只要你没有其他任何东西可以配置(所以你不能使用Springockito的配置类 - 它不支持它),但只使用模拟.还在寻找纯弹簧解决方案,如果有的话...
我很惊讶地发现,以下简单的代码示例并不适用于所有Mockito版本> 1.8.5
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Mock(name = "b2")
private B b2;
@InjectMocks
private A a;
@Test
public void testInjection() throws Exception {
assertNotNull(a.b2); //fails
assertNull(a.b1); //also fails, because unexpectedly b2 mock gets injected here
}
static class A{
private B b1;
private B b2;
}
interface B{}
}
Run Code Online (Sandbox Code Playgroud)
在javadocs(http://docs.mockito.googlecode.com/hg/latest/org/mockito/InjectMocks.html)中有一个引用:
注1:如果你有相同类型(或相同的擦除)的字段,最好用匹配的字段命名所有@Mock注释字段,否则Mockito可能会感到困惑,注入不会发生.
这是否意味着如果我有几个相同类型的字段我不能只模拟其中一个而是应该@Mock为所有相同类型的字段定义?是否已知限制,是否有任何原因尚未解决?@Mock按字段名称匹配应该是直截了当的,不是吗?
我已经阅读了很多关于如何模拟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手动启动,我希望 …
我测试的类接收客户端包装器:
测试类(snippest)
private ClientWrapper cw
public Tested(ClientWrapper cw) {
this.cw = cw;
}
public String get(Request request) {
return cw.getClient().get(request);
}
Run Code Online (Sandbox Code Playgroud)
测试初始化:
ClientWrapper cw = Mockito.mock(ClientWrapper.class);
Client client = Mockito.mock(Client.class);
Mockito.when(cw.getClient()).thenReturn(client);
//Here is where I want to alternate the return value:
Mockito.when(client.get(Mockito.any(Request.class))).thenReturn("100");
Run Code Online (Sandbox Code Playgroud)
在exmaple中我总是返回"100",但Request有一个属性id,我想client.get(Request)根据值返回不同的request.getId()值.
我该怎么做?
我是模拟框架的新手,我的工作需要模拟框架来完成单元测试.在当前的代码库中,我可以看到上面3个框架正在不同的地方用于单元测试.那么,我应该在上述3个框架中选择哪一个?
我正在从我正在进行的项目中删除Powermock,所以我试图仅用Mockito(mockito-core-2.2.28)重写一些现有的单一测试.
当我运行测试时,我有以下错误:
org.mockito.exceptions.base.MockitoException:
不能模拟/间谍类com.ExternalpackagePath.Externalclass
Mockito不能嘲笑/间谍,因为:
- 最后一堂课
我知道,这个问题已经被问(如何嘲弄与一的Mockito final类,调用final类与静态的Mockito方法Mock对象),但我没有找到我要找的答案.
这是我的代码的摘录:
public class MyClassToTest extends TestCase {
private MyClass myClass;
@Mock private Externalclass ext; // This class is final, I would like to mock it
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here
ext = Mockito.mock(Externalclass.class);
}
}
Run Code Online (Sandbox Code Playgroud)
由于文档的Mockito中提到(https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2,§Mock的unmockable),我增加了org.mockito.plugins.MockMaker文件.这是我项目的树:
我还尝试将"resources"目录放在"src"中,在一个名为"test"的子目录中,但结果仍然相同.
我认为用Mockito v2嘲笑决赛是可能的.有人知道这里缺少什么吗?
谢谢!