java - Mockito, argThat, and hasEntry -


tl;dr: these tests don't compile because type parameters don't match. changes should make make them compile , run correctly?

https://github.com/wesleym/matchertest

i have non-test code calls service. calls service's activate method map parameter.

public class foo {   private final service service;    public foo(service service) {     this.service = service;   }    public void bar() {     map<string, ?> params = getparams();     service.activate(params);   }    private map<string, ?> getparams() {     // interesting goes here   } } 

some code i'm trying test has dependency on service one:

public interface service {   public void activate(map<string, ?> params); } 

i'd test code mocking service mockito , verifying activate called reasonable map. following code works:

@test public void testexactmap() {   service mockservice = mock(service.class);   foo foo = new foo(mockservice);    foo.bar();    map<string, string> expectedparams = new hashmap<>();   expectedparams.put("paramname", "paramvalue");   verify(service).activate(expectedparams); } 

however, i'd test map contains 1 particular entry. hamcrest hasentry matcher seems perfect use case:

@test public void testhasentry() {     service mockservice = mock(service.class);     foo foo = new foo(mockservice);      foo.bar();      verify(mockservice).activate(argthat(hasentry("paramname", "paramvalue"))); } 

when try this, following error in intellij idea:

error:(31, 45) java: incompatible types: inference variable t has incompatible bounds     equality constraints: java.util.map<? extends java.lang.string,? extends java.lang.string>     upper bounds: java.util.map<java.lang.string,?>,java.lang.object 

the problem here need mockito matcher of map<string, ?>, hasentry gives me matcher of map<? extends string, ? extends string>. explicit type parameters, can't figure out reconcile "? extends" part of type parameter. should resolve error? there specific cast or explicit type parameter should use?

i understand can use argumentcaptor this. way this? possible @ hamcrest matchers?

the argthat return type not being inferred reason. try explicitly casting shown below:

 mockito.verify(foo).bar((map<string, string>) argthat(matchers.hasentry("paramname", "paramvalue"))); 

the testhasentrycast() can fixed shown below. notice cast (map<string, ?>) argthat return type:

@test public void testhasentrycast() {     service mockservice = mock(service.class);     foo foo = new foo(mockservice);      foo.bar();      verify(mockservice).activate((map<string, ?>)  argthat(hasentry("paramname", "paramvalue"))); } 

Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -