Java any class type

Mockito: List Matchers with generics

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class clazz) :

when(mock.process(Matchers.anyListOf(Bar.class))); 

Note: this is deprecated in Mockito 2.* and will be removed in Mockito 3. Deprecated because Java 8 compiler can infer the type now.

@artbristol do you know if with anySet() should work as same as anyList()? I am in Java 8 and a warning is thrown in Eclipse IDE

anyListOf is deprecated, so it is better NOT to use it. Example for Java 8 doesn’t work in case of method overload, for example if you have a method accepting 2 different lists: List and List I’ve solved this problem using ArgumentMatchers with generic: when(adapter.adapt(ArgumentMatchers.anyList())).thenCallRealMethod();

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.>any(List.class))); 

Java 8 newly allows type inference based on parameters, so if you’re using Java 8, this may work as well:

when(mock.process(Matchers.any())); 

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean «any instanceof Foo», but any() still means «any value including null «.

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers . Older versions of Mockito will need to keep using org.mockito.Matchers as above.

Источник

Java Mockito ArgumentMatchers any(Class type)

Since Mockito 2.1.0, only allow non-null instance of , thus null is not anymore a valid value. As reference are nullable, the suggested API to match null would be #isNull(). We felt this change would make test harnesses much safer than they were with Mockito 1.x.

  • For primitive types use #anyChar() family.
  • Since Mockito 2.1.0 this method will perform a type check thus null values are not authorized.
  • Since mockito 2.1.0 #any() is no longer an alias of this method.

Syntax

The method any() from ArgumentMatchers is declared as:

public static T any(Class type) 

The method any() has the following parameter:

The method any() returns

Example

The following code shows how to use ArgumentMatchers from org.mockito.

Specifically, the code shows you how to use Java Mockito ArgumentMatchers any(Class type)

import nl.knaw.huygens.timbuctoo.crud.Authorization; import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection; import nl.knaw.huygens.timbuctoo.security.exceptions.AuthorizationUnavailableException; import nl.knaw.huygens.timbuctoo.security.Authorizer; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; public class AuthorizerBuilder < public AuthorizerBuilder() < >/*w w w . d e m o 2 s . c o m */ public static Authorizer notAllowedToWrite() throws AuthorizationUnavailableException < return createAuthorizer(false); > public static Authorizer allowedToWrite() throws AuthorizationUnavailableException < return createAuthorizer(true); > static Authorizer createAuthorizer(boolean allowedToWrite) throws AuthorizationUnavailableException < Authorizer authorizer = Mockito.mock(Authorizer.class); Authorization authorization = Mockito.mock(Authorization.class); Mockito.when(authorization.isAllowedToWrite()).thenReturn(allowedToWrite); Mockito.when( authorizer.authorizationFor(ArgumentMatchers.any(Collection.class), ArgumentMatchers.anyString())) .thenReturn(authorization); return authorizer; > >
import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import name.isergius.android.task.hazpro.samplevideochat.core.MessageConsumer; import name.isergius.android.task.hazpro.samplevideochat.data.Client; import name.isergius.android.task.hazpro.samplevideochat.data.Server; /**// w w w . de m o 2 s. co m * @author Sergey Kondratyev */ @RunWith(MockitoJUnitRunner.class) public class EventRoomJoinedTest < @Mock private MessageConsumer messageConsumer; private EventRoomJoined eventRoomJoined; private JSONObject arg; private String JSON = "<\"room\":<\"clients\":[<\"id\":\"335386be-0a63-4d01-9476-759a54877b0e\",\"deviceId\":\"3f0c1829-31c8-4d5c-a01a-34b75043b393\",\"userId\":null,\"name\":\"Anonymous 335386be-0a63-4d01-9476-759a54877b0e\",\"streams\":[\"0\"],\"isOwner\":false,\"isAudioEnabled\":false,\"isVideoEnabled\":true,\"socketId\":\"7iEdwsJDeiW28RMUDFXV\",\"role\":<\"roleName\":\"visitor\">>,>],\"name\":\"/t\",\"owners\":[],\"sfuServer\":null,\"iceServers\":<\"iceServers\":[<\"url\":\"turn:turn.appear.in:443?transport=udp\",\"urls\":\"turn:turn.appear.in:443?transport=udp\",\"username\":\"appearin:1487733517\",\"credential\":\"Cbi9jjvM/pWOcOsfeGxLOeQbcOU=\">,,]>,\"isClaimed\":true,\"type\":\"free\",\"isFollowEnabled\":true,\"isLocked\":false,\"knockers\":[],\"knockPage\":<>>,\"selfId\":\"82c7cd22-6b7d-4866-ab7d-4a1aa2c85403\">"; @Before public void setUp() throws Exception < arg = new JSONObject(JSON); eventRoomJoined = new EventRoomJoined(messageConsumer); > @Test public void call() throws Exception < Client expectedClient = new Client("82c7cd22-6b7d-4866-ab7d-4a1aa2c85403", null, null, null); expectedClient.add(new Server("Cbi9jjvM/pWOcOsfeGxLOeQbcOU appearin:1487733517", "turn:turn.appear.in:443?transport=udp")); expectedClient.add(new Server("Cbi9jjvM/pWOcOsfeGxLOeQbcOU appearin:1487733517", "turn:turn.appear.in:443?transport=tcp")); expectedClient.add(new Server("Cbi9jjvM/pWOcOsfeGxLOeQbcOU appearin:1487733517", "turns:turn.appear.in:443?transport=tcp")); eventRoomJoined.call(arg); Mockito.verify(messageConsumer).selfData(expectedClient); Mockito.verify(messageConsumer).clientData(ArgumentMatchers.any(Client.class)); > >
import com.bergamin.tdd.api.retrofit.client.AuctionWebClient; import com.bergamin.tdd.exception.NewBidLowerThanHighestBidException; import com.bergamin.tdd.exception.UserExceedsNumberOfBidsLimitException; import com.bergamin.tdd.model.Auction; import com.bergamin.tdd.model.Bid; import com.bergamin.tdd.model.User; import com.bergamin.tdd.ui.dialog.AlertDialogManager; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class BidSenderTest < @Mock/* w w w . d e m o 2 s . c o m */ private AuctionWebClient client; @Mock private BidSender.ProcessedBidListener listener; @Mock private AlertDialogManager manager; @Mock private Auction auction; private User alex = new User("Alex"); private User fran = new User("Fran"); @Test public void shouldShowErrorMessage_whenBidLowerThanCurrentBid() < BidSender sender = new BidSender(client, listener, manager); doThrow(NewBidLowerThanHighestBidException.class).when(auction).bid(ArgumentMatchers.any(Bid.class)); sender.send(auction, new Bid(fran, 100)); verify(manager).showAlertWhenBidLowerThanHighestBid(); > @Test public void should_ShowErrorMessage_whenUserExceedsBidLimit() < BidSender sender = new BidSender(client, listener, manager); doThrow(UserExceedsNumberOfBidsLimitException.class).when(auction).bid(ArgumentMatchers.any(Bid.class)); sender.send(auction, new Bid(alex, 200)); verify(manager).showAlertWhenUserExceedsNumberOfBidsLimit(); > >

  • Java Mockito ArgumentMatchers isNull()
  • Java Mockito ArgumentMatchers anyMap()
  • Java Mockito ArgumentMatchers any()
  • Java Mockito ArgumentMatchers any(Class type)
  • Java Mockito ArgumentMatchers anyBoolean()
  • Java Mockito ArgumentMatchers anyByte()
  • Java Mockito ArgumentMatchers anyChar()

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Mockito.any() pass Interface with Generics

There is a type-safe way: use ArgumentMatchers.any() and qualify it with the type:

ArgumentMatchers.any() — IDE hints me that Explicit type arguments can be inferred. It means that there is no requirement to explicitly define types and ArgumentMatchers.any() will have the same result

But hold on! any() and any(Class) do not do the same thing. The no-arg matches anything, but the 1-arg only matches things of that class. So how can do you this where, like the original poster, you need to use any(Class) and not any() ?

Using Java 8, you can simply use any() (assuming static import) without argument or type parameter because of enhanced type inference. The compiler now knows from the target type (the type of the method argument) that you actually mean Matchers.>any() , which is the pre-Java 8 solution.

I’m wondering about a situation where the argument type is generic as well, but you only want to mock it for one concrete type (or mock it for multiple types in different ways). Given when(x.y(any())).thenAnswer(. ) for example, where y is public T y(AsyncCallback arg) . Perhaps it would be better to check the type in the answer, if that is what’s needed?

@MatthewRead Due to erasure, the actual type cannot be checked at runtime by Mockito. So you can’t even use isA() . If the object holds a Class object corresponding to the type, and the interface exposes this, I guess you could check it in a custom matcher. Or for example in case of a Collection you could check the type of the elements.

Источник

Passing Any Type As A Method Parameter [duplicate]

I am trying to have a method that can take in ANY TYPE as a parameter (Object, int, boolean, ArrayList, etc.). Here is a very simple method to illustrate what it would be trying to do:

public void printAnything(Type arg0)

I am not sure, but I think Object should do the job, as every object is derived from Object and every normal type (int, boolean. ) can get autoboxed, so you should also be able to pass them as arguments.

Yes, of course. And if I remember right, if you can pass an Integer , but give an int , Java automatically converts it to its object representation, this also works the other way round, depending on what’s needed. This is called autoboxing, I think.

4 Answers 4

In your specific example, Object would fit well because PrintStream#println(Object obj) would print the string representation (using String#valueOf(Object) ).

When you pass a primitive value, it will be automatically boxed into its wrapper type, e.g an int would be converted to java.lang.Integer which extends Object .

public void printAnything(Object arg0)
public void printAnything(T arg0)

Both versions can also be called with primitives thanks to auto-boxing.

The data type you need to accept is Object .

Because in Java, everything is derived from it, except the primitive data types like int , float , boolean , etc.
Those however can also be passed if Object is required, because Java automatically converts between primitives (e.g. int ) and their object representation (e.g. Integer ), depending on which form fits the method prototype. This feature is called autoboxing.

Источник

Читайте также:  Open php file from html
Оцените статью