spring boot - Failing while testing autowired field using Junit -
am new junit, solution below issue welcomed. have main class like,
@service public class mainclass extends abstractclass { @autowired classa a; @autowired objectmapper mapper; public void methoda(){ .... anotherclass obj= (anotherclass)mapper.readerfor(anotherclass.class).readvalue(some_code); ....... }
test class is,
@runwith(powermockrunner.class) @preparefortest({mainclass.class}) public class mainclasstest { @mock classa a; @mock objectmapper mapper; @injectmocks mainclass process = new mainclass(); //i have somthing autowired mapper class of main in test class @test public void testprocessrequest() throws exception{ process.methoda() }
am getting null mapper object in main class while testing, yes aware haven't dne kind of initialization. there better way writing junit mapper. note : tried @mock objectmapper throws exception @ "readerfor". in advance.
you not have use mockito/powermock. use spring boot test. this:
import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; import com.fasterxml.jackson.databind.objectmapper; @runwith(springrunner.class) @springboottest public class someservicetest { @autowired private someservice service; @autowired private objectmapper om; @test public void try_me(){ system.out.println(om); } }
adding info more question. if want use mockito objectmapper should prepare mock. if not when calling readerfor(...) mock returns null default , later, in readvalue method, getting nullpointer.
a basic preparation mock might be:
objectreader or = mockito.mock(objectreader.class); mockito.when(or.readvalue(mockito.anystring())).thenreturn(new instance of object); mockito.when(mapper.readerfor(user.class)).thenreturn(or);
Comments
Post a Comment