争论的Mockito匹配器(如any,argThat,eq,same,和ArgumentCaptor.capture())表现非常不同,从Hamcrest匹配器.
Mockito匹配器经常导致InvalidUseOfMatchersException,即使在使用任何匹配器后执行很长时间的代码中也是如此.
Mockito匹配器受到奇怪的规则的影响,例如,如果给定方法中的一个参数使用匹配器,则只需要对所有参数使用Mockito匹配器.
当覆盖Answers或使用(Integer) any()等时,Mockito匹配器可能会导致NullPointerException .
使用Mockito匹配器以某种方式重构代码可能会产生异常和意外行为,并且可能完全失败.
为什么Mockito匹配器是这样设计的,它们是如何实现的?
我是eclipse的新手,想做以下事情:
make all.我使用shell脚本来构建我的项目; 我如何在Eclipse环境中使用它?make all).我该如何解决这个问题?
我正在使用Mockito和Junit来测试应用程序,我需要在模拟时向HttpServletRequest添加标头.这是我第一次使用模拟概念来测试应用程序.在使用这个模拟概念时,我们如何设置标题来请求对象?
Java代码:
@Produces({ MediaType.APPLICATION_JSON })
@Path("/devices")
public class DvrRestService {
private static final Logger logger = LoggerFactory.getLogger(DvrRestService.class);
private DvrMiddleService dvrMiddleService;
@Inject
public DvrRestService(DvrMiddleService dvrMiddleService) {
this.dvrMiddleService = dvrMiddleService;
}
@GET
@Path("/{deviceId}/metadata")
public Response getDeviceMetadata(@Context HttpServletRequest request, @PathParam("deviceId") String deviceId,
@RequiredSession final Session session) {
try {
public static String[] REQUEST_HEADERS = { "if-none-match" };
List<String> requiredHeaders = Lists.newArrayList(REQUEST_HEADERS);
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) { // here gettting NullPointerException
String headerName = headerNames.nextElement(); …Run Code Online (Sandbox Code Playgroud) 我有一个设计问题.下面是TimeStamp接口
/**
* <T> Type of Timestamp. For ex: Date, long, Calendar etc
*
*/
public interface TimeStamp<T> extends Comparable<TimeStamp<T>>
{
/**
* Returns the timestamp.
* @return
*/
public T getTimeStamp();
}
Run Code Online (Sandbox Code Playgroud)
我基本上想要一个List只能包含TimeStamps的类.在列表中添加任何内容基本上取决于时间戳.应该如何成为我的List类声明.
如果我决定合成,代码将如下所示:
public class TimeList<T> implements List<TimeStamp<T>>
{
private List<TimeStamp<?>> list = new ArrayList<TimeStamp<?>>();
//other list methods who will return based on list above
.....
}
Run Code Online (Sandbox Code Playgroud)
但上述内容没有意义.例如,如果我有一个类DefaultTimeStamp implments TimeStamp<Long>并将TimeList实例化为
TimeList<DefaultTimeStamp> l = new TimeList<DefaultTimeStamp>();
Run Code Online (Sandbox Code Playgroud)
然后任何电话l.add(elem)都会期待TimeStamp<DefaultTimeStamp>哪个是错的.
声明:public class TimeList<TimeStamp<T>> …
我正在将一些测试从 Mockito 1.x 转换为 2.15.0。
对于字符串参数来说,处理“null”值的新方法相对简单。对于 Map 参数来说,这似乎有点困难,但我认为使用类型参数的任何类型都会遇到同样的问题。
我尝试过以下替代方案:
anyMap()isNull()nullable(Map.class)(Map<KeyType,ValueType>) nullable(Map.class)第一个是 2.x 转换之前的原始版本。如果值为空则不匹配。如果值始终为空,则第二个有效,但我不喜欢它,因为它会在测试中删除类型信息。第三个似乎是正确的,但它无法编译,因为形式参数类型使用泛型。第四部作品很成功,但我不喜欢那里的演员阵容。
有没有更清洁的解决方案?
我正试图用Mockito实现这种行为:
当类型O的对象应用于方法M时,mock应该对类型为O的对象执行另一个方法,将其自身作为参数传递.
毕竟有可能吗?
我试图理解用于JUnit的TestRunner(package junit.textui)类的设计模式.TestRunner类正在扩展一个监听器并具有监听器的引用.
如果是Observer设计模式,那为什么要扩展监听器呢?它应该只有听众的参考.
在打字稿中:
let str: string = 'abc';
let val: unknown = 'test';
if (typeof val === 'string') {
str = val;
}
// this code does not report any error, everything works fine.
Run Code Online (Sandbox Code Playgroud)
但是,如果我稍微改变一下代码:
if ((typeof val) === 'string') {
str = val;
}
// add the () to hold typeof val;
// error report in typescript in this line: str = val !
Run Code Online (Sandbox Code Playgroud)
这真的让我很困惑,谁能帮忙解释一下这里发生了什么。
我想模拟我的存储库上提供的查询,如下所示:
@Test
public void GetByEmailSuccessful() {
// setup mocks
Mockito.when(this.personRepo.findAll()
.stream()
.filter(p -> (p.getEmail().equals(Mockito.any(String.class))))
.findFirst()
.get())
.thenReturn(this.personOut);
Mockito.when(this.communityUserRepo.findOne(this.communityUserId))
.thenReturn(this.communityUserOut);
...
Run Code Online (Sandbox Code Playgroud)
我的@Before方法看起来像这样:
@Before
public void initializeMocks() throws Exception {
// prepare test data.
this.PrepareTestData();
// init mocked repos.
this.personRepo = Mockito.mock(IPersonRepository.class);
this.communityUserRepo = Mockito.mock(ICommunityUserRepository.class);
this.userProfileRepo = Mockito.mock(IUserProfileRepository.class);
}
Run Code Online (Sandbox Code Playgroud)
可悲的是,当我运行测试时,我收到错误:
java.util.NoSuchElementException:没有值存在
当我双击错误时,它指向.get()第一个lambda 的方法.
有没有人成功嘲笑过一个lambda表达式并知道如何解决我的问题?
我在我的项目中使用 Mockito 和 Spring Framework。
我有一个这样的测试用例:
class SomeTest {
@Mock
SomeDao dao;
@InjectMock
TestTarget target;
class MyAnswer implements Answer {
//some method here
}
}
Run Code Online (Sandbox Code Playgroud)
我想MyAnswer为定义一个自定义答案类dao。
如果没有注释,我可以Mockito.mock(Dao.class, new MyAnswer())使用 MyAnswer 来强制我的模拟对象。但我发现通过@Mock注释,它们只接受enum AnswerslikeAnswers.RETURNS_DEFAULT或内部的参数Answers.RETURNS_MOCKS。
我可以强制dao使用MyAnswer注释@Mock吗?