How to mock ATG RqlStatement - mockito

Inside my ATG Droplet, I am fetching records from repository. Now when I try to mock RQLStatement it throws a org.mockito.exceptions.misusing.MissingMethodInvocationException
Below are the statements I am trying to mock:
final RepositoryView view = this.getRepository().getView("product");
final RqlStatement statement = RqlStatement.parseRqlStatement("id = ?0");
prodItems = statement.executeQuery(view, params);
I used mockito and powermockito but its not working
PowerMockito.mockStatic(RqlStatement.class);
PowerMockito.when(RqlStatement.parseRqlStatement("id =?0")).thenReturn(this.statementmock);
Mockito.when(this.statementmock.executeQuery(this.viewMock, params)).thenReturn(new RepositoryItem[4]);

Adding #PrepareForTest annotation .working for me now

Related

Mockito how can simule record doesn't exist

.exception.INSSTaxNotFoundException: INSS Tax not found with ID 1
Could someone help me?
I want mokite "inssTaxService.findById", I don't know how do.
I get this error: INSSTaxNotFoundException: INSS Tax not found with ID 1.
But I could like found the record and go on.
Can I do that in Service or Not?
#Test
void whenINSSTaxIdInformedThenReturnThisINSSTax() throws INSSTaxNotFoundException {
INSSTaxDTO expectedSavedInssTaxDTO = INSSTaxBuilder.builder().build().toINSSTaxDTO();
INSSTax expectedSavedInssTax = inssTaxMapper.toModel(expectedSavedInssTaxDTO);
when(inssTaxService.findById(expectedSavedInssTaxDTO.getId())).
thenReturn(expectedSavedInssTaxDTO);
assertEquals(expectedSavedInssTax.getId(), expectedSavedInssTaxDTO.getId());
assertEquals(expectedSavedInssTax.getDescription(), expectedSavedInssTaxDTO.getDescription());
assertEquals(expectedSavedInssTax.getSocialSecurityRatePercent(), expectedSavedInssTaxDTO.getSocialSecurityRatePercent());
}
What you might be missing is actually injecting the mock of inssTaxService inside your class which you are testing,
Your code would be something like this. Considering its a pure java code(not spring boot etc, you can change the code accordingly in that case).
Mock the service(Which i feel you have done else Mockito would have thrown and error)
InssTaxService mockedInssTaxService = Mockito.mock(InssTaxService.class);
//other impl on this mock for this e.g
when(mockedInssTaxService.findById(expectedSavedInssTaxDTO.getId())).
thenReturn(expectedSavedInssTaxDTO);
Inject the mocked object to the ClassToTest.
ClassToTest classToTest = new ClassToTest(mockedInssTaxService);
If you are using spring boot test you can use #MockBean or #Mock and #InjectMocks instead of new keyword

"No tests found for given includes" when using TestNG with Groovy

I'm trying to use Test NG with Groovy. I implemented a simple test class, but whenever I try to run it I get the following error:
No tests found for given includes: [tests.OTP.get]
Here is what the tests.OTP class looks like:
class OTP{
public static Logger log = LogManager.getLogger(HomePage.class.getName())
String environment = 'qatesting'
String number = '0769878787'
#Test
def get(){
// SoapuiOTP s = new SoapuiOTP(environment,number)
// s.getOTP()
log.info("hello")
Assert.assertEquals(0,System.getProperty("SOAPUI_OTP"))
log.info System.getProperty('SOAPUI_OTP')
}
}
I use the play button (IntelliJ) next to the def get() to run the test but i get the same error on class level. Please assist, I've tried invaliding my cache and restarting. I have looked at TestNG No tests found. Nothing was run and
TestNG - no tests were found, but it didn't help.
You need to replace def with void in the method annotated with #Test. As the documentation says:
Test methods are annotated with #Test. Methods annotated with #Test that happen to return a value will be ignored, unless you set allow-return-values to true in your testng.xml:
<test allow-return-values="true">
Source: https://testng.org/doc/documentation-main.html#test-methods
The def return type compiles to Object, not void, so TestNG ignores this method by default.
This misconception is not TestNG specific and can be done in JUnit as well: Running Groovy test cases with JUnit 5

Mockito with newInstance method

I have a class-under-test that has the following code :
public void getDetails (String message){
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
StringReader strReader = new StringReader(message);
InputSource inputSrc = new InputSource(strReader);
Document doc = docBuilder.parse(inputSrc);
...
}
I want to write a JUnit for this piece of code using Mockito.
I tried various things like :
DocumentBuilderFactory docBuilderFactoryMock = Mockito.mock(DocumentBuilderFactory.class);
Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(docBuilderFactoryMock);
But I get the Exception:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
DocumentBuilderFactory$$EnhancerByMockitoWithCGLIB$$23223735 cannot be returned by toString()
toString() should return String
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
If I do the following:
DocumentBuilderFactory docBuilderFactoryMock = Mockito.spy(DocumentBuilderFactory.newInstance());
DocumentBuilder documentBuilderMock = Mockito.mock(DocumentBuilder.class);
Mockito.when(docBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilderMock);
docBuilderdocBuilderMockito.when(docBuilderFactoryMock.newDocumentBuilder()).thenReturn(docBuilderFactoryMock);
and debug my code then I see that the class-under-test does not use my Mock objects anywhere but creates its own objects and throws a SAXParseException at
Document doc = docBuilder.parse(inputSrc);
Unit testing is intended to test your components/classes, not the library components/classes that are used.
Your class is parsing a String as xml content and to test that, you will find that providing a set of xml Strings with known output is the best way to test.
Simply pass a known xml String to your class under test and assert that the resulting model that is parsed, contains the data that you expect for that xml content.
I don't think that you need any mocking.

Mocking DbEntityEntry

I am writing unit tests for my Generic Repository layer but i have some problems with DbEntityEntry.
My Update method is like below.
public virtual void Update(TEntity entityToUpdate) {
var entity = dbSet.Find(context.Entry<ITrackedEntity>(entityToUpdate).Entity.Id);
context.Entry(entity).CurrentValues.SetValues(entityToUpdate);
}
As you can see, context.Entry<TEntity>(TEntity entity) method is invoked by caller. So while unit tests this code throws null exception.
I had tried to mock context.Entry method but i couldn't because i couldn't provide return value.
My current test method is below
[Fact]
public void UpdateTest() {
AssetType _sample1 = new AssetType() {
AssetTypeID = 1,
IsContainer = true,
Name = "Sample 1"
};
IDbSet<AssetType> assetTypeDbSet = new FakeDbSet<AssetType>(_sample1);
Mock<IDbContext> mockContext = new Mock<IDbContext>();
mockContext.Setup(pc => pc.Set<AssetType>()).Returns(assetTypeDbSet);
_sample1.Name = "Sample 1.1";
var dbEntity = mockContext.Object.Entry<ITrackedEntity>(_sample1);
mockContext.Setup(p => p.Entry<ITrackedEntity>(It.IsAny<AssetType>())).Returns(dbEntity);
using(GenericRepository<AssetType> repo = new GenericRepository<AssetType>(mockContext.Object)) {
repo.Update(_sample1);
var result = repo.GetAll(0, 0);
Assert.Equal(1, result.Count);
var singleResult = repo.GetByID(1);
Assert.Equal(_sample1.Name, singleResult.Name);
}
}
I tried to get DbEntityEntry value by calling context.Entry<>() method at test but that wa returned null, too.
Also this class cannot be iniated with new operator. So i stucked..
And what is the point of unit testing this code? You fake the Find method, then you fake DbEntityEntry and there will be no real logic to test.
Anyway EF code is not unit testable in general. That is one reason why people believe that repository will help them because they mock / fake their repository when testing upper layer. Repository is then tested with integration tests to make sure that everything in EF and database works as expected.
You will not fake DbEntityEntry with Moq. Maybe with TypeMock Isolator or MS Fakes you will be able to do more but it is not needed in your sample code.

AssertWasCalled on method in SystemUnderTest

I'm getting into TDD; using nUnit and RhinoMocks 3.5.
I'm trying to figure out how to AssertWasCalled on a method in the SystemUnderTest (SUT). My understanding is that you can't mock the system under test. In fact, my current test results in an exception because the I'm using the AssertWasCalled on the SUT.
OrdersPresenter:
public void OnViewLoad_GetOrders()
{
var orders = GetOrders();
View.Model.Orders = orders;
}
public List<Orders> GetOrders()
{
return _ordersRepository.GetAll();
}
OrdersPresenterTest:
_ordersPresenter = new OrdersPresenter(_view, _ordersRepository);
[Test]
public void OnViewLoad_GetOrders_Should_Call_GetOrders()
{
_view.Raise(v => v.LoadOrders += _ordersPresenter.OnViewLoad_GetOrders, view, new EventArgs);
_ordersPresenter.AssertWasCalled(d => d.GetOrders); // Getting non-mock exception here
}
How do I Assert GetOrders was called in the SUT? I haven't been able to figure it out in the docs.
Any help is greatly appreciated.
Edit:
I understand the GetOrders method in the SUT should be private. I went back thru Roy Osherove's Art of Unit Testing to see how to test private methods. Roy says making a method public (to test against) is not necessarily a bad thing, so I will keep it public.
So I've written a test for GetOrders and I assert the return value ShouldBe a list of orders. That said, I believe I need to restructure my test for OnViewLoad_GetOrders by stubbing the value I get from GetOrders and asserting the results of my actions on that object.
Can someone confirm and explain?
You can not use AssertWasCalled() on not-mocked objects. Just abstract class OrdersPresenter by an interface (use Extract Interface refactoring technique) and then
var ordersPresenter = MockRepository.GenerateMock<IOrderRepository>();
view.Raise(...);
_ordersPresenter.AssertWasCalled(d => d.GetOrders);
BTW,
for me it is not clear why RhinoMocks not used generic parameter constraint for AssertWasCalled
public static void AssertWasCalled<T>(this T mock, Action<T> action,
Action<IMethodOptions<object>> setupConstraints)
Basically T is not limited, but I believe it would be better limit it to somethign like IMockMarkerInterface

Resources