I'm using Mockito and PowerMockito to instantiate a mock when a constructor is called:
#RunWith(MockitoJUnitRunner.class)
#PrepareForTest(ConVibe.class)
public class ConVibeTests {
ConVibe task;
#Mock ShapeEffect shapeEffect;
#Test
public void verify_shape_effect() {
whenNew(ShapeEffect.class).withAnyArguments().thenReturn(shapeEffect);
task.call();
// Omitted
}
// Omitted
}
This is the call to the constructor that I wanted to mock, located inside the function call() in the class conVibe:
final ShapeEffect effect = new ShapeEffect(mode, new RepService());
The fact is that the real constructor is called (where there is a DB call that obviously fail) instead of creating a mock.
What's wrong?
You're using the wrong runner - if you want to use PowerMock, you need to use the PowerMockRunner:
#RunWith(PowerMockRunner.class)
#PrepareForTest(ConVibe.class)
public class ConVibeTests {
Related
I have a service class that extends another service with a constructor. This class has an autowired field and a method that I wanted to unit test using Mockito. However, I am having trouble writing a unit for it.
Let say the service looks somewhat like this:
#Service
public class SomeService extends Service {
#Autowired
private SomeClient someClient;
public SomeService(Product product, #Qualifier(Constants.SOME_BEAN) Details temp) {
super(product, temp);
}
#Override
public State create() {
Request request = new Request();
request.set...
request.set..
Status status = someClient.createTenant(request);
..
.. // construct a State object and return
}
}
Now, I am writing a test for this class and I am trying to unit test the method create() above. I am having trouble mocking someClient there when this method is called by my test.
The test class looks somewhat like:
#RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
private Detail temp;
private SomeFacade service;
private SomeClient someClient;
private Product product;
#Before
public void setup() {
temp = mock(Details.class);
product = mock(Product.class);
service = spy(new SomeService(product, temp));
someClient = mock(SomeClient.class);
}
#Test
public void test() {
Status status = new Status();
status.setStatus(...);
when(someClient.createTenant(any())).thenReturn(status);
State state = service.create();
// asserts
}
}
What I want to is that when I call service.create in the test above, the call
someClient.createTenant(request); in the method tested should be mocked to return a value and this is something I am not able to get working. Any help?
We can use Mockito's #InjectMocks-annotation to inject mocks into our unit under test. For this, we also need to
remove mock intialization from the setup()-method and
annotate the mocks with #Mock
Remarks:
Instead of field injection, I would recommend constructor injection. This allows, among other things, to keep the structure of the code and create the unit under test within setup() by manual injection
I would also recommend to add a type to the when: when(someClient.createTennant(any(Request.class)))...
As was pointed out by #second, the spy on the unit under test is superfluous.
Also pointed out by #second was the fact that field injection will not work if a constructor is present
I am new to Android unit testing and I am using Mockito to do it.
I want to test my method which has a method from another class. I want to stub that method so that it should not be called. I am using doReturn().when() so that original method is not called but it is calling the original method.
Here is my code:
doReturn(true).when(myclass1mock).methodofclass1();
boolean a = myclass1mock.methodofclass1(); //here it return true
class2spy.methodofclass2(anyvalue);
The method I am testing is:
public class2 {
public void methodofclass2(Value) {
boolean value = class1.methodofclass1(); //here I don't want to call this method
}
}
The problem is method of class1 is called everytime. I want something so that class1.methodofclass1() is not called.
I am injecting using:
#Mock
class1 myclass1mock;
#InjectMocks
class2 myclass2;
#Before
public void setUp() {
myclass2 = new myclass2();
class2spy = Mockito.spy(myclass2);
}
As you want to test the behavior of Class2, then i think you mixed up the annotations. Also i would take advantage of #Spy annotations rather that configuring it by hand:
#Spy
class1 myclass1Spy;
#InjectMocks
class2 myclass2;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
Also, do not try not to spy the class which is being under test (class2). Use the real implementation.
I have a Singleton class that I want to test. It uses a #Inject annotation for that class's contructor. Now for testing I want to call a public method for that class in my test class but unable to do so. I have mocked an object that is getting passed to the constructor.
#Inject
private SomeClass(SomeOtherClassObject obj) {
super(obj);
}
I mocked the above private constructor in the following way:
Singleton mockSingleton = PowerMock.createMock(Singleton.class);
PowerMock.expectNew(Singleton.class).andReturn(mockSingleton);
I dont understand how do I call the following method
public SomeClass someMethod(int 1, String 2){
//some logic
return (Object of SomeClass)
}
Any help will be appreciated. Thank You.
If you are using guice as well, you can provide a module in your test that binds SomeOtherClassObject to your mock instance. Then create the SomeClass instance via Guice's injector.
#Test
public void test() {
SomeOtherClassObject other = ...; // what ever you need to create the Mock
Injector injector = Guice.createInjector(new AbstractModule(){
public void configure() {
bind(SomeOtherClassObject.class)toInstance(other);
}
});
SomeClass some = injector.getInstance(SomeClass.class); // guice takes care of the constructor injection
some.someMethod(...);
}
If you dont use guice, have a look at needle4j. Its a test-support lib that automatically injects mocks when injection is required. But it works only with easymock or mockito.
I am doing some tests for the class Export
I need to mock a method so I made a mockito (I am new to Mockito)
public Class ExportServiceImpl implements ExportService{
#Autowired
Service service
public void export(){
String exportString = service.getPath();
domoreStuff() ....
}
And
public Class ServiceImpl implements Service(){
public String getPath(){
return "thePath";
}
}
I need to mock the getPath() method so I did in the TestNG
public class ExportTestNG(){
public textExport(){
Service serviceMock = Mockito.mock(Service.class);
Mockito.when(serviceMock.getData()).thenReturn("theNewPath");
System.out.println("serviceMock.getData() : " + serviceMock.getData()); // prints "theNewPath", OK
exportService.export(); // the getData() is not the mockito one
}
}
I may have not correclt mockito and I may not have understood how it works.
Any idea ?
You can use Mockito to inject the mocks for you and avoid having to add setter methods.
#RunWith(MockitoJUnitRunner.class)
public class ExportTestNG(){
#InjectMocks
private ExportServiceImpl exportService;
#Mock
private Service serviceMock;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
public textExport(){
Mockito.when(serviceMock.getData()).thenReturn("theNewPath");
exportService.export();
}
}
You need to wire the mock service into the exportService object.
If you have a setter for the service member variable then do this:
exportService.setService(serviceMock);// add this line.
exportService.export();
If you don't have a setter you will need to perform the wiring before calling export.
Options for this include:
Set the value of the service member variable using reflection.
Write a test-only version of the Service and use a test-only version of the spring configuration xml files.
Something else (that I have never done and thus don't know about).
For a test I like to create a new instance of ComplicatedClass . In reality it's very complicated to crate this instance, but I don't need the real constructor to run nor any of it's data. All I need is an object of ComplicatedClass. How can I do that?
public class ComplicatedClass {
public ComplicatedClass(/* lots of dependencies */) {
}
}
#Test
public class SomeTest {
public void test1() {
ComplicatedClass complicatedInstance = /* new ComplicatedClass(); /*
AnotherClass ac = new AnotherClass(complicatedInstance);
/* ... */
}
}
#Tested annotation does this:
#Tested ComplicatedClass complicatedInstance;
That's it. Please note that the above won't do any mocking. It is just convenient way of creating instances without calling consturctors, etc.
If you want ComplicatedClass to be mocked, use #Mocked annotation:
#Mocked ComplicatedClass complicatedInstance;
In this case, you also get your instance automatically created, but the instance is mocked.
#Tested internally instantiates the class object.
But in case of Junit test case writing of singleton class how #Tested internally creates instance because for singleton private constructor is there.