Java mockito when any

Вызовы mock-методов с параметрами

Предыдущие правила добавленные мок-объекту касались методов без параметров. А как создавать правила для методов с параметрами? Более того, хотелось бы создавать правила, чтобы при одних значениях параметров был один результат, а при других – другой.

Так тоже можно делать. Если вы хотите, чтобы при определенном параметре метод возвращал что-то определенное, то правило можно записать так:

Mockito.doReturn(результат).when(объект).имяМетода(параметр);

И сразу рассмотрим пример, чтобы лучше все понять. Пусть наш List возвращает имя Иван при запросе 10-го элемента, и имя Марья при запросе 500-го. Сказано – сделано.

 @ExtendWith(MockitoExtension.class) class ParamsTest < @Mock List mockList; @Test public void whenMockAnnotation() < //добавление первого правила Mockito.doReturn("Иван").when(mockList).get(10); //добавление второго правила Mockito.doReturn("Марья").when(mockList).get(500); assertEquals("Иван", mockList.get(10)); assertEquals("Марья", mockList.get(500)); > > 

4.2 Шаблоны параметров

И сразу хитрые коллеги зададут мне вопрос: “А как быть, если метод требует аргументы, но при любых значениях должен возвращать один и тот же результат?”. Не будем же мы писать:

 Mockito.doReturn("Иван").when(mockList).get(1); Mockito.doReturn("Иван").when(mockList).get(2); Mockito.doReturn("Иван").when(mockList).get(99); 

Нет, никто тебя так писать не заставляет. Если ты хочешь добавить правило mock-объекту, которое действует для метода с любыми аргументами, то для этого есть специальный объект:

Читайте также:  Python requirements txt file

Наш пример с его помощью будет записан так:

Mockito.doReturn("Иван").when(mockList).get(any(int.class));

Есть тут пара нюансов. Объект Mockito.any() имеет тип Object , поэтому для параметров разных типов есть его аналоги:

Метод Тип параметра
1 any() Object, включая null
2 any(ClassName.class) ClassName
3 anyInt() int
4 anyBoolean() boolean
5 anyDouble() double
6 anyList() List

Более корректно наш пример будет выглядеть так:

Mockito.doReturn("Иван").when(mockList).get(anyInt());

4.3 Метод doAnswer()

Мы добрались до сложного поведения виртуальных методов. Рано или поздно наступит ситуация, когда ты захочешь, чтобы этот виртуальный метод имел сложное поведение. Например, он должен возвращать значения в зависимости от параметров, преобразовывать строку в верхний регистр.

Для этого есть специальный метод – doAnswer() , в который передается функция, которая делает то, что тебе нужно:

Mockito.doAnswer(функция).when(объект).имяМетода(параметр);

Давай заставим метод get() класса List возвращать квадрат переданного ему аргумента. И напишем такую программу:

 @ExtendWith(MockitoExtension.class) class DoAnswerTest < @Mock List mockList; @Test public void whenMockAnnotation() < Mockito.doAnswer(invocation ->< int parameter = invocation.getArgument(0); return parameter * parameter; >).when(mockList).get(anyInt()); assertEquals(100, mockList.get(10)); assertEquals(25, mockList.get(5)); > > 

Функцию мы задали с помощью объект класса Answer.

Источник

Mockito Argument Matchers — any(), eq()

Mockito Argument Matchers - any(), eq()

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.

Mockito Argument Matchers — any()

Sometimes we want to mock the behavior for any argument of the given type, in that case, we can use Mockito argument matchers. Mockito argument methods are defined in org.mockito.ArgumentMatchers class as static methods. Let’s say we have a class defined as:

class Foo < boolean bool(String str, int i, Object obj) < return false; >int in(boolean b, List strs) < return 0; >int bar(byte[] bytes, String[] s, int i) < return 0; >> 
Foo mockFoo = mock(Foo.class); when(mockFoo.bool(anyString(), anyInt(), any(Object.class))).thenReturn(true); 

We are stubbing bool() method to return “true” for any string, integer and object arguments. All the below assertions will pass in this case:

assertTrue(mockFoo.bool("A", 1, "A")); assertTrue(mockFoo.bool("B", 10, new Object())); 

Mockito Argument Matcher — eq()

When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method.

when(mockFoo.bool(eq("false"), anyInt(), any(Object.class))).thenReturn(false); assertFalse(mockFoo.bool("false", 10, new Object())); 
when(mockFoo.in(anyBoolean(), anyList())).thenReturn(10); 
any(byte[].class) any(Object[].class) 

Mockito AdditionalMatchers

Mockito org.mockito.AdditionalMatchers class provides some rarely used matchers. We can specify arguments to be greater than, less than, perform OR, AND, NOT operations. We can also check for equality of arrays.

when(mockFoo.bar(any(byte[].class), aryEq(new String[] < "A", "B" >), gt(10))).thenReturn(11); 

So if we call bar() method with any byte array as argument, second argument as < “A”, “B” >and third argument greater than 10, then the stubbed method will return 11. Below assertions will pass for our stubbed method.

assertEquals(11, mockFoo.bar("abc".getBytes(), new String[] < "A", "B" >, 20)); assertEquals(11, mockFoo.bar("xyz".getBytes(), new String[] < "A", "B" >, 99)); 

Mockito Verify Argument Matchers

Mockito argument matchers can be used only with when() and verify() methods. Let’s look at a few examples of using argument matchers in Mockito verify method.

verify(mockFoo, atLeast(0)).bool(anyString(), anyInt(), any(Object.class)); verify(mockFoo, atLeast(0)).bool(eq("false"), anyInt(), any(Object.class)); 

Summary

Mockito argument matcher methods are very useful in stubbing behaviors in a generic way. There are many methods to cover almost all the requirements. You can look at more Mockito examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Mockito When/Then Cookbook

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Overview

This cookbook shows how to use Mockito to configure behavior in a variety of examples and use cases.

The format of the cookbook is example focused and practical — no extraneous details and explanations are necessary.

And of course, if you want to learn more about testing well with Mockito, have a look at the other Mockito articles here.

Further reading:

Mockito Verify Cookbook

Mockito – Using Spies

Mockito’s Mock Methods

We’re going to be mocking a simple list implementation, which is the same implementation we used in the previous cookbook:

public class MyList extends AbstractList  < @Override public String get(final int index) < return null; >@Override public int size() < return 1; >> 

2. The Cookbook

Configure simple return behavior for mock:

MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenReturn(false); boolean added = listMock.add(randomAlphabetic(6)); assertThat(added).isFalse();

Configure return behavior for mock in an alternative way:

MyList listMock = mock(MyList.class); doReturn(false).when(listMock).add(anyString()); boolean added = listMock.add(randomAlphabetic(6)); assertThat(added).isFalse();

Configure mock to throw an exception on a method call:

MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenThrow(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> listMock.add(randomAlphabetic(6)));

Configure the behavior of a method with void return type — to throw an exception:

MyList listMock = mock(MyList.class); doThrow(NullPointerException.class).when(listMock).clear(); assertThrows(NullPointerException.class, () -> listMock.clear()); 

Configure the behavior of multiple calls:

MyList listMock = mock(MyList.class); when(listMock.add(anyString())) .thenReturn(false) .thenThrow(IllegalStateException.class); assertThrows(IllegalStateException.class, () -> < listMock.add(randomAlphabetic(6)); listMock.add(randomAlphabetic(6)); >);

Configure the behavior of a spy:

MyList instance = new MyList(); MyList spy = spy(instance); doThrow(NullPointerException.class).when(spy).size(); assertThrows(NullPointerException.class, () -> spy.size());

Configure method to call the real, underlying method on a mock:

MyList listMock = mock(MyList.class); when(listMock.size()).thenCallRealMethod(); assertThat(listMock).hasSize(1);

Configure mock method call with custom Answer:

MyList listMock = mock(MyList.class); doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); String element = listMock.get(1); assertThat(element).isEqualTo("Always the same");

3. Conclusion

The goal of this guide is to have this information readily available online. I’ve published a few similar development cookbooks on Google Guava and Hamcrest and now Mockito.

The implementation of all these examples and code snippets can be found on GitHub. This is a Maven-based project, so it should be easy to import and run as it is.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью