Method inside "When" actually being called - mockito

When I am testing a class A (TestNG) which uses some methods from some other class Helper Class
I am mocking the helper class(Mockito) for testing class A.
but when(helper.methodUsedByClassA(value)).thenReturn(new HashMap>())
this line of code is actually calling helper.methodUsedByClassA and a null pointer exception is thrown (because of data I am using for testing is not valid)
why is this happening? Why would the method name inside mockito "when" actually be called ?
class ATest{
#Mock
private Helper helper;
private A target;
#BeforeTest
public void setUp() {
MockitoAnnotations.initMocks(this);
this.target = new UpdateDigicatKdpAsinUtil(helper);
}
#Test(dataProvider = "data")
public void testMethod(List<String> value) {
when(helper.methodUsedByClassA(value)).thenReturn(new HashMap<String, List<String>>({{put("test", new ArrayList<>())}}));
}
#DataProvider
public Object[][] data(){
List<String> list = new ArrayList<>();
return new Object[][]
{
{list}
}
}
class Helper{
public Map<String, List<String>> methoUsedByClassA(int value) {
//This method is being executed because it is mentioned inside "when"
}
}

I guess you get an NPE because helper is NULL.
The problem is that the #Mock annotation isn't processed and because of that, the variable helper isn't initialized.
You have to annotate the test class with #RunWith(MockitoJUnitRunner.class). MockitoJUnitRunner will process the #Mock annotation and create the mock.

Related

ArgumentCaptor for a generic list always returns an empty list

When trying to capture an ArrayList parameter with an ArgumentCaptor the resulting object is always an empty list.
I am using the #Captor annotation to create my ArgumentCaptor but it still results in an empty list being returned.
#RunWith(MockitoJUnitRunner.class)
public class Test{
#Mock
private Service service;
#Captor
private ArgumentCaptor<ArrayList<SomeType>> secondCaptor;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
}
#Test
public void shouldDoStuffWithListValues(){
ArgumentCaptor<SomeType> captor = ArgumentCaptor.forClass(SomeType.class);
//...
verify(service).doStuff(captor.capture(), secondCaptor.capture()));
SomeType type = captor.getValue();
List<SomeType> someTypeList = secondCaptor.getValue();
//this assert is fine
Assert.assertTrue(type != null);
//whereas; this assert always fails, despite the call containing a value
Assert.assertTrue(someTypeList.size()>0);
}
}

how to convert return type of method within when().thenReturn method of Mockito

Below is my code snippet. This is giving me compilation error, as env.getProperty will return String. How do I get integer value. Interger.ParseInt is not working.
when(this.env.getProperty("NeededIntegerValue")).thenReturn(15);
Below is my test class
public class MyclassTest {
Myclass myObj=new Myclass();
#Mock Environment env=Mockito.mock(Environment.class);
#Before
public void init() {
when(this.env.getProperty("StringKey1")).thenReturn("Stringvalue");
when(this.env.getProperty("StringKey2")).thenReturn(intValue);
myObj.setEnvironment(this.env);
}
#Test
public void testTenantIdentifierCutomerTypeCUSTOMER_ACCOUNT() {
assertEquals("Expecteddata",myObj.testMethod(new StringBuilder(inputData),anotherData).toString);
}
}
Below is the Method needs to be tested
public StringBuilder testMethod(StringBuilder inputData, String anotherData)
{
if (anotherData.equals(env.getProperty("StringKey1"))) {
inputData=inputData.append(","+arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))]);
}
}
First, you should mock your env, this way:
when(this.env.getProperty("StringKey1")).thenReturn("StringValue");
when(this.env.getProperty("StringKey2")).thenReturn("StringRepresentationOfYourInt");
Second, pay attention to the method itself, should be
arrayOfInputData[Integer.parseInt(env.getProperty("StringKey2"))
not
arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))
Instead of
myObj.setEnvironment(this.env); in init() method try:
#InjectMocks
Myclass myObj = new Myclass();
Also remove assignment for
#Mock Environment env=Mockito.mock(Environment.class);
it should look
#Mock Environment env;

Mock a decorated Stream using PowerMockito

So I have a class which takes an OutputStream in the constructor and creates a PrintWriter from it inside a method. Question is how do I get this PrintWriter to verify it?
Example public Class(OutputStream output) {}
public void foo() {
PrintWriter writer = new PrintWriter(output);
}
What I try to do is:
PrintWriter writer = PowerMockito.mock(PrintWriter.class)
PowerMockito
.whenNew(PrintWriter.class)
.withArguments(output)
.thenReturn(writer);
However I get that there are no interractions with this writer. Any help would be appreciated.
It will be better if you provided full code snippet with PowerMock configuration. Then I could help you and give advise, now I may only guess what could be wrong, but I'm trying:
The PrintWriterhas several constructors which could accept OutputStreamand PowerMock have a defect that it could incorrect guess which constructor is mocked, when you pass only arguments when a class had overloaded constructors.
Also it could be common mistake, you haven't added the class which create an instance of PrintWriter to #PrepareForTest.
So, worked example in base on my assumption case:
public class PrintWriterCreator {
private final PrintWriter printWriter;
public PrintWriterCreator(OutputStream outputStream) {
this.printWriter = new PrintWriter(outputStream);
}
public void write(String message){
printWriter.write(message);
}
}
Test class:
#RunWith(PowerMockRunner.class)
#PrepareForTest({PrintWriter.class, PrintWriterCreator.class})
public class PrintWriterCreatorTest {
#Mock
private OutputStream outputStream;
#Mock
private PrintWriter printWriterMock;
private PrintWriterCreator printWriterCreator;
#Before
public void setUp() throws Exception {
whenNew(PrintWriter.class).withParameterTypes(OutputStream.class).withArguments(eq(outputStream)).thenReturn
(printWriterMock);
printWriterCreator = new PrintWriterCreator(outputStream);
}
#Test
public void testWrite() throws Exception {
String message = "someMessage";
printWriterCreator.write(message);
verifyNew(PrintWriter.class).withArguments(outputStream);
verify(printWriterMock).write(eq(message));
}
}

Mockito - Testing method that calls private methods

I was trying to find solution but haven't found yet. I tried to test public method which has calls of the couple of private ones inside. One of the problem that private method retrieves Hibernate's Criteria by generic method that in its turn retrieves it through chain of another generic methods. Please take a look at the code below. Frankly I'm not sure that it is possible to test that case but if anyone has ideas please suggest them:
ConcreteDao
public class ConcreteDao extends EntityDao<ConcreteEntity> {
public Class<ConcreteEntity> getClassType() {
return ConcreteEntity.class;
}
}
EntityDao
public abstract class EntityDao<T> extends AbstractDao<T>{
public List<T> getEntityByFilter(EntityFilter filter) {
Criteria criteria = getCriteriaByFilter(filter.getFilters());
criteria.setMaxResult(filter.getMaxResult());
criteria.setFirstResult(filter.getFirstResult());
criteria.addOrder(Order.asc(filter.getSortedField()));
criteria.list();
}
private Criteria getCriteriaByFilter(List<CustFilter> filters) {
Criteria criteria = getCriteria();
for (CustFilter filter : filters) {
filter.addrestrictionToCriteria(criteria, filter.getProperty(), filter.getValue());
}
return criteria;
}
}
AbstractDao
public abstract class AbstractDao<T> {
private EntityManagerFactory entityManagerFactory;
public abstract getClassType();
public Criteria getCriteria() {
return getSession().createCriteria(getClassType());
}
public Session getSession() {
Session session = (Session) getEntityManager().getDelegate();
return session;
}
public EntityManager getEntityManager() {
entityManagerFactory.getEntityManager();
}
}
Test class
#RunWith(MockitoJUnitRunner.class)
public class ConcreteDaoTest {
#Mock
private EntityManager entityManager;
#Mock
private Session session;
#Mock
private Criteria criteria;
private List<CustFilter> filters;
private EntityFilter entityFilter;
private List<ConcreteEntity> resultList;
#InjectMocks
private ConcreteDao concreteDao = new ConcreteDao;
public void init() {
filters = new ArrayLis<CustFilter>();
CustFilter custFilter = new CustFilter();
//fill filter;
filters.add(custFilter);
entityFilter = new EntityFilter();
//fill entityFilter
entityFilter.setFilters(filters);
ConcreteEntity concreteEntity = new ConcreteEntity();
resultList = new ArrayList<ConcreteEntity>();
resultList.add(concreteEntity);
}
#Test
public void getEntityByFilterTest() {
when(concreteDao.getEntityManager).thenReturn(entityManager);
when(concreteDao.getSession()).thenReturn(session);
when(concretedao.getCriteria()).thenReturn(criteria);
when(filter.getFilters()).thenReturn(filters);
when(filter.getMaxResult()).thenReturn(10);
when(filter.getFirstResult()).thenReturn(0);
when(filter.getSortedField()).thenReturn("firstName");
when(criteria.list()).thenReturn(resultList);
List<ConcreteEntity> result = concreteDao.getEntityByFilter(entityFilter);
Assert.assertThen(result. is(notNullValue()));
}
}
With Mockito, you cannot mock private method calls.
Try PowerMockito with which you can mock any kinds of methods like static methods, private methods, local method instantiations and so on.

JAXB/MOXy: How to partially unmarshall, passing the descendants of a given node to a closed/proprietary class?

I'm starting with some Java classes that I would like to be able to unmarshall from XML--I'm determining the schema as I go. I would like to use XML similar to the following:
<Person fname="John" lname="Doe">
<bio><foo xmlns="http://proprietary.foo">Blah <bar>blah</bar> blah</foo></bio>
</Person>
I'm hoping to annontate my Java classes similar to the following:
public class Person {
#XmlAttribute
public String fname;
#XmlAttribute
public String lname;
#XmlElement
public ProprietaryFoo bio;
}
I'd like to pass the <foo xmlns="http://proprietary.foo"> element and it's descendants to a compiled factory class which works like this:
FooFactory.getFooFromDomNode(myFooElement) // Returns a private ProprietaryFooImpl as an instance of the public ProprietaryFoo Interface
It seems like I need to create a DomHandler for ProprietaryFoo but I'm not quite able to figure it out (I was getting “com.xyz.ProprietaryFooImpl nor any of its super class is known to this context.") I'm also interested in XmlJavaTypeAdapter I can't figure out how to receive the ValueType as an Element.
Ended up using both an XmlAdapter and a DomHandler along with a simple Wrapper class.
public class FooWrapper {
#XmlAnyElement(FooDomHandler.class)
public ProprietaryFoo foo;
}
public class FooXmlAdapter extends XmlAdapter<FooWrapper, ProprietaryFoo> {
#Override
public ProprietaryFoo unmarshal(FooWrapper w) throws Exception {
return w.foo;
}
#Override
public FooWrapper marshal(ProprietaryFoo f) throws Exception {
FooWrapper fooWrapper = new FooWrapper();
fooWrapper.foo = f;
return fooWrapper;
}
}
/* The vendor also provides a ProprietaryFooResult class that extends SAXResult */
public class FooDomHandler implements DomHandler<ProprietaryFoo, ProprietaryFooResult> {
#Override
public ProprietaryFooResult createUnmarshaller(ValidationEventHandler validationEventHandler) {
return new ProprietaryFooResult();
}
#Override
public ProprietaryFoo getElement(ProprietaryFooResult r) {
return r.getProprietaryFoo();
}
#Override
public Source marshal(ProprietaryFoo f, ValidationEventHandler validationEventHandler) {
return f.asSaxSource();
}
}
For whatever reason, this didn't work with the standard classes from the com.sun namespace but MOXy handles it well.

Resources