Wanted to but not invoked. Mockito - mockito

I have a question. Maybe it is very basic. Can we do this
without actually invoking the method in our test class?
My Test class:
class Test{
Action action=new Action();
#Mock
Provider provider;
when(provider.getNames()).thenReturn(Arrays.asList("names"));
verify(provider,atLeastOnce()).getNames();
action.update();
}
As you can see, "provider" is only mocked and not explicitly called. The only way it will be called is when I invoke action.update(); I am getting the error
Wanted but not invoked: Actually, there were zero interactions with this mock.
provider.getNames()
class Action{
public void update(){
Provider provider = new Provider();
List<String> l=provider.getNames();
}
}

Your order of operations is wrong. If provider is called when action.update() is called, then you should be verifying after calling action.update():
when(provider.getNames()).thenReturn(Arrays.asList("names"));
action.update(); // Do action first
verify(provider,atLeastOnce()).getNames(); // Then verify outcome of "action"
UPDATE
Your code is not currently testable:
public void update(){
Provider provider = new Provider();
List<String> l=provider.getNames();
}
Your code says "when update is called, make a NEW provider and call getNames on that". Your test says "assert that this random provider that does interact with action at all is called", which will of course never pass.
You need to use dependency injection to pass in the provider you want to use to verify the interaction.
Either pass the provider to the function:
public void update(Provider provider){
List<String> l=provider.getNames();
}
So you can test like this:
action.update(provider)
verify(provider).getNames()
OR pass the provider via constructor:
class Action {
private final Provider mProvider;
// Default constructor can be used in main app as usual
public Action() {
this(new Provider())
}
// Argument constructor can receive a provider that can be mocked
public Action(Provider provider) {
mProvider = provider;
}
public void update(){
// Provider provider = new Provider(); // Don't do this
List<String> l = mProvider.getNames(); // Use constructor provided object
}
Then you can test this:
#Test
public void test() {
Action action = new Action(provider); // Inject mock
action.update();
verify(provider).getNames(); // Now our mock will get called
}

Related

Mockito: How to test a class's void method?

Unit test noob here.
I have three classes: Db1Dao, Db2Dao, ExecuteClass where Db1Dao, Db2Dao are database access objects for two different databases. My goal is to fetch some data from db1 using Db1Dao and run executeClass.execute() to "put" the processed data into db2 using Db2Dao.
My ExecuteClass looks like this:
class ExecuteClass {
private Db1Dao db1Dao;
private Db2Dao db2Dao;
public void execute() {
...
List<String> listOfString = getExternalData(someParam);
List<Metadata> metadatum = db1Dao.get(someInputs);
... I do something to generate a list of new class `A` based on listOfString & metadatum ...
try {
db2Dao.put(listOfA);
} catch (PutException e){
...
}
}
public List<String> getExternalData(SomeClass someParam){
... do something
return listOfString;
}
}
Now I want to test:
Given a specific listOfString (returned by getExternalData) and a specific metadatum (returned by db1Dao.get):
Will I get the desired listOfA?
Am I able to call db2Dao.put and its input parameter is listOfA?
Particularly, I have hard-coded sample listOfString and metadatum and desired listOfA (and they will be passed via an object MockData, see the following code) but I don't know how to write the test using Mockito. The following is a test class I wrote but it does not work:
class TestClass extends BaseTest {
#Mock
private Db1Dao db1Dao;
#Mock
private Db2Dao db2Dao;
private ExecuteClass executeClass;
#BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
executeClass = new ExecuteClass(db1Dao, db2Dao);
}
#ParameterizedTest
#MethodSource("MockDataProvider")
public void executeClassTest(final MockData mockData) throws PutException {
Mockito.when(db1Dao.get(Mockito.any(), ...))
.thenReturn(mockData.getMetadatum());
ExecuteClass executeClassSpy = Mockito.spy(executeClass);
Mockito.when(executeClassSpy.getExternalData(Mockito.any()))
.thenReturn(mockData.getListOfString());
executeClassSpy.execute();
// executeClass.execute(); not working neither...
List<A> listOfA = mockData.getDesiredListOfA();
Mockito.verify(db2Dao).put(listOfA);
}
}
Could anyone please let me know? Thank you in advance!!
You should not create a spy of the same class you want to test. Instead, try to write a unit test for the smallest amount of code (e.g. a public method) and mock every external operator (in your case Db1Dao and Db2Dao).
If testing a public method involves calling another public method of the same class, make sure to mock everything inside the other public method (in your case getExternalData). Otherwise, this other public method might be a good candidate for an extra class to have clear separation of concerns.
So, remove the ExecuteClass executeClassSpy = Mockito.spy(executeClass); and make sure you setup everything with Mockito what's called within getExternalData.
To now actually, verify that Db2Dao was called with the correct parameter, either use your current approach with verifying the payload. But here it's important to 100% create the same data structure you get while executing your application code.
Another solution would be to use Mockito's #Captor. This allows you to capture the value of why verifying the invocation of a mock. Later on, you can also write assertions on the captured value:
#Captor
private ArgumentCaptor<ClassOfListOfA> argumentCaptor;
#Test
public void yourTest() {
Mockito.verify(db2Dao).put(argumentCaptor.capture());
assertEquals("StringValue", argumentCaptur.getValue().getWhateverGetterYouHave);
}
The following code worked for me.
I partially accepted #rieckpil's answer. I used #Captor which is very handy.
The reason I had to mock getExternalData() is because its implementation is still a "TODO".
class TestClass extends BaseTest {
#Mock
private Db1Dao db1Dao;
#Mock
private Db2Dao db2Dao;
#Captor
private ArgumentCaptor<List<A>> argumentCaptor;
private ExecuteClass executeClass;
#BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
executeClass = new ExecuteClass(db1Dao, db2Dao);
}
#ParameterizedTest
#MethodSource("MockDataProvider")
public void executeClassTest(final MockData mockData) throws PutException {
Mockito.when(db1Dao.get(Mockito.any(), ...))
.thenReturn(mockData.getMetadatum());
ExecuteClass executeClassSpy = Mockito.spy(executeClass);
Mockito.when(executeClassSpy.getExternalData(Mockito.any()))
.thenReturn(mockData.getListOfString());
executeClassSpy.execute();
List<A> listOfA = mockData.getDesiredListOfA();
Mockito.verify(db2Dao).put(argumentCaptor.capture());
assertEquals(listOfA, argumentCaptor.getValue());
}
}

How to mock or prepare test methods in case we called private method inside the method?

While writing a testCase for Controller class,The private method that is getServiceContext(). has different object because
one we are passing serviceContext from testclass and other object inside the controller class itself call itself.Due to this Foo object is null. how to resolve this.
public class Controller {
#Refernce
private FooService fooService;
public CustomData getDetails(String id){
Foo foo = fooService.getFoo(id ,**getServiceContext()**);
//getServiceContext() is different object
System.out.println("foo data>>>> "+foo); // **Throwing null pointer exceptions**
CustomData customData = new CustomData();
customData.setStudentName(foo.getName);
customData.setStudentName(foo.getId);
...
...
...
return customData;
}
private ServiceContext getServiceContext() {
ServiceContext serviceContext = new ServiceContext();
serviceContext.setCompanyId(context..);
serviceContext.setUserId(context..);
...
....
retrn serviceContext;
}
}
public class ControllerTest {
#InjectMocks
private Controller controller;
#Mock
private FooService fooService;
private Foo foo;
#BeforeEach
public void setUp() throws PortalException {
foo = mock(Foo.class);
}
#Test
public void getDetailsTest() throws Exception {
ServiceContext **serviceContext** = new ServiceContext();
serviceContext.setCompanyId(context..);
serviceContext.setUserId(context..);
...
....
Mockito.when(fooService.getFoo("testId",serviceContext)).thenReturn(foo);
System.out.println("Service context>>>> "+**serviceContext**); // different serviceContext object
CustomData customData = controller.getDetails("testId");
Assertions.assertThat(ss).isNotNull();
}
}
There are multiple ways to do that.
First, we can mock with anyOf(Type.class), that will actually match object type rather than value.
Mockito
.when(fooService.getFoo(Mockit.eq("testId"), Mockito.any(ServiceContext.class)))
.thenReturn(foo);
this will work as expected and return the desired value.
Additionally, if you want to check with what data serviceContext object is being passed as arg in service method, (as we just checked object type rather than value), We can use ArgumentCaptor for that.
It basically captures argument data which is being passed in the method call.
let's create ArgumentCaptor for service context
#Mock
private FooService fooService;
#Captor
private ArgumentCaptor<ServiceContext> captor;
Now, let's capture the argument during verification.
Mockito.verify(fooService).getFoo(Mockit.eq("testId"), captor.capture());
Assertions.assertEquals("value of x in context", captor.getValue().getX());
Basically here, captor.getValue() returns service context object which is being passed. So, you can verify all data you want to validate in that object.
Alternate, Approach would be Spy which will basically spy on the class under test and you can control the behavior of private methods in test class itself.
To do that, we need to add #Spy annotation along with #InjectMocks on test class.
#Spy
#InjectMocks
private Controller controller;
Now, you can mock the private method and return the expected value.
Mockito.doReturn(serviceContextValue).when(controller).getServiceContext();
and use that object for mocking fooService.
Mockito.verify(fooService).getFoo("testId", serviceContextValue);
But when using Spy, don't forget to write unit test for private method as it's mocked, it's business logic will not be tested by above test cases. that's a reason, it's not recommended way.
I would suggest using ArgumentCaptor approach.

ServiceStack: Accessing the IRequest in the Service returns null

I am using Servicestack. I have a base class for my Services, like so:
public abstract class ServiceHandlerBase : Service
and then some methods and properties in there of interest. I already have several methods that accesses the IRequest object, like:
protected AlfaOnline GetContactItem()
{
string deviceUUID = Request.Headers.Get(Constants.DEVICE_UUID); // <-- calling this method from constructor will give NullRef on Request here
string authToken = Request.Headers.Get(Constants.AUTH_TOKEN);
// do stuff
return existingContactItem;
}
which works well inside my service implementations, no problems there.
Now, I wanted to use this exact same method directly from the base class, calling it in the constructor:
public ServiceHandlerBase()
{
AlfaOnline ao = GetContactItem();
}
but I then get a NullReferenceException on the Request object as noted above.
When is the Request object ready to access and use? Because it's not null inside the service implementations.
You can't access any dependencies like IRequest in the constructor before they've been injected, they're only accessible after the Service class has been initialized like when your Service method is called.
You can use a Custom Service Runner to execute custom logic before any Service is Executed, e.g:
public class MyServiceRunner<T> : ServiceRunner<T>
{
public override void OnBeforeExecute(IRequest req, TRequest requestDto) {
// Called just before any Action is executed
}
}
And register it with ServiceStack in your AppHost with:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext ctx)
{
return new MyServiceRunner<TRequest>(this, ctx);
}
But if you just want to run some logic for a Service class you can now override OnBeforeExecute() in your base class, e.g:
public abstract class ServiceHandlerBase : Service
{
public override void OnBeforeExecute(object requestDto)
{
AlfaOnline ao = GetContactItem();
}
}
See ServiceFilterTests.cs for a working example.
If you're implementing IService instead of inheriting the Service base class you can implement IServiceBeforeFilter instead.
The new Service Filters is available from v5.4.1 that's now available on MyGet.

Invalid signature for SetUp or TearDown method - What am I doing wrong?

I am trying to do some dependency injection for my tests using nUnit. I'm new to TDD and nUnit so it's possible I am missing something simple. So basically I've created a SetUp method for my interfaces. I originally was using a constructor but I read it's bad to do this when doing TDD so I now using a method.
When I run my test I construct an object and assign it to the interface and then I call a method using that interface. I want to test if it can parse a string decimal.
When I run my test it says test failed and the message is:Invalid signature for SetUp or TearDown method
See below for the actual code:
public class DonorTests
{
private IDonor _Donor;
private IValidateInput _ValidInput;
//DonorTests(IDonor donor, IValidateInput validInput)
//{
// _Donor = donor;
// _ValidInput = validInput;
//}
[SetUp]
void Setup(IDonor donor, IValidateInput validInput)
{
_Donor = donor;
_ValidInput = validInput;
}
[Test]
public void HandleStringNotDecimal()
{
_ValidInput = new ValidateInput();
Assert.IsTrue(_ValidInput.IsDecimal("3445.3450"));
}
}
My class that uses this interface
public class ValidateInput : IValidateInput
{
public decimal RoundTwoDecimalPlaces(decimal amount)
{
return Math.Round(amount);
}
public bool IsDecimal(string amount)
{
decimal ParsedDecimal;
return Decimal.TryParse(amount, out ParsedDecimal);
}
public decimal ConvertToString(string value)
{
decimal ParsedDecimal;
Decimal.TryParse(value, out ParsedDecimal);
return ParsedDecimal;
}
}
You're injecting dependencies using constructor injection previously, right? I think you will not be able to perform dependency injection using method decorated with SetUpAttribute because such method has to be parameterless. Also Setup method has to be public, see this SO thread.
How are we typically dealing with similar situations in our company is:
[TestFixture]
public class DonorTests
{
private IDonor _Donor;
private IValidateInput _ValidInput;
[SetUp]
public void Setup()
{
_Donor = new Donor();
_ValidInput = new ValidateInput();
}
[Test]
public void HandleStringNotDecimal()
{
Assert.IsTrue(_ValidInput.IsDecimal("3445.3450"));
}
}
Or if construction of ValidInput and Donor is cheap then we simply create new instance for each test, having special method for that purpose so when we decide to test another implementation of IValidateInput then it is enough to change it in one place only:
[TestFixture]
public class DonorTests
{
[Test]
public void HandleStringNotDecimal()
{
var validInput = CreateValidateInput();
Assert.IsTrue(validInput .IsDecimal("3445.3450"));
}
private static IValidateInput CreateValidateInput()
{
return new ValidateInput();
}
}
Besides the cause mentioned in the accepted answer, I have met the same error when leaving method as non-public (private or protected).
NUnit most probably relies on reflection and does not deal with non-public methods, so special methods (i.e. decorated with NUnit specific attributes) must be public.

Powermock to mock instance methods called from other executing methods

In this code, i have mocked the one of the ValidateHandlerSoapClient class method which is instantiated and called this method (soapClientSpy.processSoapRequestRespons) in validateMsisdnHandlerIRSpy.validate().So soapClientSpy.processSoapRequestResponse is not working , instead the real method is called.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ValidateMsisdnHandler.class,ValidateHandlerSoapClient.class})
public class Demo {
MessageControl messageControl=PowerMockito.mock(MessageControl.class);
Validate validate=PowerMockito.mock(Validate.class);
ValidateMsisdnHandlerIR validateMsisdnHandlerIRSpy = PowerMockito.spy(new ValidateMsisdnHandlerIR());
ValidateHandlerSoapClient soapClientSpy = PowerMockito.spy( new ValidateHandlerSoapClient());
#Before
public void initialize() throws Exception
{
PowerMockito.when(validate.getAccountId()).thenReturn("0879221485");
PowerMockito.doReturn(true).when(validateMsisdnHandlerIRSpy, "isPrePaid",anyString());
MemberModifier.field( ValidateMsisdnHandlerIR.class, "endDate").set(
validateMsisdnHandlerIRSpy, "10-FEB-2015");
PowerMockito.when(soapClientSpy.processSoapRequestResponse(anyString())).thenReturn(true);
PowerMockito.whenNew(ValidateHandlerSoapClient.class).withNoArguments().thenReturn(soapClientSpy);
}
#Test
public void testValidateMsisdn_Cr6_Roverprempay_Not_Roverpayg() throws Exception{
Response response = validateMsisdnHandlerIRSpy.validate(validate,messageControl);
}
Replace
ValidateHandlerSoapClient soapClientSpy = PowerMockito.spy( new ValidateHandlerSoapClient())
with
ValidateHandlerSoapClient soapClientMock = PowerMockito.mock(ValidateHandlerSoapClient.class)
A spy by default just calls the methods of the underlying regular class. What you want to do is (presumably) nothing when the methods of the soap client are called.
Then of course you will need to make also change:
PowerMockito.whenNew(ValidateHandlerSoapClient.class).withNoArguments().thenReturn(soapClientMock);

Resources