mockito

一文让你快速上手 Mockito 单元测试框架

£可爱£侵袭症+ 提交于 2021-01-29 04:36:01
前言 在计算机编程中,单元测试是一种软件测试方法,通过该方法可以测试源代码的各个单元功能是否适合使用。为代码编写单元测试有很多好处,包括可以及早的发现代码错误,促进更改,简化集成,方便代码重构以及许多其它功能。使用 Java 语言的朋友应该用过或者听过 Junit 就是用来做单元测试的,那么为什么我们还需要 Mockito 测试框架呢?想象一下这样的一个常见的场景,当前要测试的类依赖于其它一些类对象时,如果用 Junit 来进行单元测试的话,我们就必须手动创建出这些依赖的对象,这其实是个比较麻烦的工作,此时就可以使用 Mockito 测试框架来模拟那些依赖的类,这些被模拟的对象在测试中充当真实对象的虚拟对象或克隆对象,而且 Mockito 同时也提供了方便的测试行为验证。这样就可以让我们更多地去关注当前测试类的逻辑,而不是它所依赖的对象。 1 生成 Mock 对象方式 要使用 Mockito,首先需要在我们的项目中引入 Mockito 测试框架依赖,基于 Maven 构建的项目引入如下依赖即可: <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.3.3</version> <scope>test</scope> </dependency>

Create Junit test for Void method

和自甴很熟 提交于 2021-01-28 20:33:55
问题 I am learning unit testing, I have some confusion, I have one Void method, Can you please explain to me how can I create a unit test for this method. public void eat(Food food){ mAmountOfEatenFood += food.eatFood(mNeededAmountOfFood - mAmountOfEatenFood); if(mAmountOfEatenFood == mNeededAmountOfFood){ System.out.println(mName + " has eaten " + mAmountOfEatenFood + " and will not be hungry for a while.."); mAmountOfEatenFood = 0; mIsHungry = false; }else{ System.out.println(mName + " has eaten

How can we mock session values (request.getSession() ) in JUnit?

泄露秘密 提交于 2021-01-28 18:51:12
问题 private BankApp processSelection(HttpServletRequest request, String[] facets, String selectedText) { DebugUtility.debug(LOG, "Enter into JiraController :: processDashBoardPortFolioSelection()"); BankApp project = new BankApp(); List<BankApp> dataAgg = (List<BankApp>) request.getSession() .getAttribute(PROJECT_WISE_SESSION); if (CollectionUtils.isNotEmpty(dataAgg)) { List<BankApp> projects = new ArrayList<>(); for (String currentProjectId : facets) { Project currProject = vendorUtils

How to mock external dependencies for final objects?

走远了吗. 提交于 2021-01-28 12:31:43
问题 public class A{ private final B b; public void meth() { //Some code Integer a = b.some_method(a,fun(b)); //Some code } private fun(int b) { return b; } } when(b.some_method(anyInt(),anyInt())).thenReturn(100) How to mock the externally dependency when writing unit tests for class A. When i mock dependency in the above way, the value of "a" is not getting assigned to 100 as expected. 回答1: Actually the answer of Jakub is correct. Maybe you need an example to understand how to do it. Check the

An exception or error caused a run to abort: org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress()L

做~自己de王妃 提交于 2021-01-28 09:02:01
问题 My environment is Intellij, SBT, Scala and Play. What might be causing the following exception? It doesn't happen all the time. At times I am unable to run my test cases due to the following exception. I am using "org.mockito" % "mockito-core" % "2.24.5" % "test", I suspect there might be some library mismatch or inconsistency but I can't figure out what it is? I have tried to clean/recompile the project (sbt) but haven't been able to solve the issue. An exception or error caused a run to

Unit test - How to mock parameters of third-party-library class Dio in flutter

浪尽此生 提交于 2021-01-28 06:30:23
问题 I am trying to test a simple repository class which make a network call using the Dio package that is a dependency injection. Requirement of the Http.post is to send a Map object to a URL with the headers of 'Content-Type': 'application/json . You can see this below: class AuthenticateUserRemoteDataSourceImpl implements AuthenticateUserRepository { final Dio httpClient; AuthenticateUserRemoteDataSourceImpl({@required this.httpClient}); @override Future<Either<Failure, AuthenticateUser>>

How do i write unit test for function with void return type

回眸只為那壹抹淺笑 提交于 2021-01-28 05:41:54
问题 I am new to writing Unit tests. I saw few examples of jUnit , but they all were for functions returning a value. I have to write unit test for following method. Also we are using objects and methods in this method not belonging to this class like ConfigParser and ParseConfig. How do i go about writing Unit tests for such menthods? @RequestMapping(value = "/generate-json" , consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) @PageType(pageType = "PlaceHolderPageType")

How to unit test “repeatWhen” in RxJava server polling

爷,独闯天下 提交于 2021-01-28 05:41:43
问题 This is my code return Observable.defer(() -> mApi.verifyReceipt(username, password)) .subscribeOn(Schedulers.io()) .doOnNext(this::errorCheck) .repeatWhen(observable -> observable.delay(1, TimeUnit.SECONDS)) .takeUntil(Response::body) .filter(Response::body) .map(Response::body); It keeps polling and receives a "false" boolean response and stops polling when "true" is received. I've made a test case for the onNext() case like: @Test public void testVerifyReceiptSuccessTrueResponse() {

How to mock @PrePersist method?

故事扮演 提交于 2021-01-27 11:50:23
问题 How do I mock a @PrePersist method, e.g. preInit(), of an entity that I instantiate? I'm using TestNG. EasyMock is prefered. @Test(enabled = true) public void testCreateOrder() { // Instantiating the new mini order will automatically invoke the pre-persist method, which needs to be mocked/overwritten! MiniOrder order = new MiniOrder(); order.setDate(new Date()); order.setCustomerId(32423423); } The MiniOrder.java is an entity that has a pre-persist method. Again, the one I like to mock

How can I mock Google's Geocoding API request using mockito/powermock?

不打扰是莪最后的温柔 提交于 2021-01-27 04:25:30
问题 I want to unit test this method using mockito/powermock: @Service public class GoogleApiService { private static final Logger logger = LoggerFactory.getLogger(GoogleApiService.class); private static final String LANGUAGE = "es"; private List<AddressType> addressTypes = Arrays.asList( AddressType.LOCALITY, AddressType.ADMINISTRATIVE_AREA_LEVEL_2, AddressType.ADMINISTRATIVE_AREA_LEVEL_1, AddressType.COUNTRY ); @Autowired private GeoApiContext geoApiContext; public String getLocalityFromLatLng