How to test this boolean method in Junit? - java

Please need to test this method paramsRequired but not as it can reproduce the behavior for testing. How to know if when passing the null parameters the method will skip the if?
My class service
public class TestStack {
private GeoClassService service;
public Address getAddress(String city,String neighborhood, boolean listOut) {
List<GeoLocation> listLocation = new ArrayList<>();
FutureTask<List<GeoLocation>> returnLoc = null;
Address location = new Address();
boolean paramsRequired = city!=null || neighborhood!=null;
if (listOut && paramsRequired) {
returnLoc = new FutureTask<>(() ->
service.getAdrres(city,neighborhood, listOut));
execute.executor(returnLoc);
}
return location;
}
}
my unit test
public class TestStackTests {
#InjectMocks
private TestStack stack;
#Test
public void paramsTest() {
Address paramsRequired = Mockito.spy(stack.getAddress(
"any city", "any", true));
boolean newAddres = paramsRequired==null;
Assert.assertFalse(newAddres);
}
}
I don't think I'm testing anything but honestly, I don't know how to do this test

Related

Mockito -- Response from service returns null in test - Java

I'm working on testing a class. This class calls on a service (let's say its called client, and we want to call client.put())
put() should return a response, but at least in the test, the response is null
I don't know if I just didn't setup the mock correctly and wanted to sanity check with you guys here
public class ATest {
#Mock
private ServiceProto.PutItemsResponse res;
...(private variables)...
#Before
public void setUp() throws Exception {
client = mock(Client.class);
clientFactory = mock(ClientFactory.class);
when(clientFactory.get(any())).thenReturn(client);
...(initializing private vars for constructor as mock variables, example below...)
captionConverter = mock(CaptionToCTItemConverter.class);
when(privateVar.convert(any(obj.class))).thenReturn(Item.newBuilder().build());
classAToTest = spy(new ClassAToTest(private variables);
}
#Test
public void putItem() {
long id = 4710582L;
AObject aObject = testUtils.getObject();
doReturn(res).when(client).putItems(any(ServiceProto.PutItemsRequest.class));
System.out.println("result is "+ res);
try {
classAToTest.putMethod(aObject);
}
catch (NullPointerException e) {
}
verify(creativeToolsClient, Mockito.times(1)).putItems(any(IngestionServiceProto.PutItemsRequest.class));
}
}
And this is the method being tested
public void putMethod(AObject aObject) {
final String id = Long.toString(aObject.getId());
ServiceProto.PutItemsResponse putItemsResponse = null;
Exception putItemsFailure = null;
putItemsResponse =
client.putItems(ServiceProto.PutItemsRequest.newBuilder()
.putItems(
id,
ServiceProto.PutItemsRequest.Item.newBuilder()).build())
.build());
if (putItemsResponse == null) {
logger.warning("PutItems request has failed: "+
(putItemsFailure == null ? "null" : putItemsFailure.getMessage()));
}
}
and when I run it it gives the warning
The putItems method works for other people. Did I set up mock incorrectly?
res variable is not initialized. To mock objects with #Mock annotation use
#ExtendWith(MockitoExtension.class)
public class ATest {
...

In Java, How to test void method in Junit Mockito with assertion?

How to test void methods in Mockito with assertSame or assertEquals. I am able to do verify only.
i am getting sonar or PMD rules violation -"JUnit tests should include assert() or fail()".
Below is my sample class with test class.
#Service
public class MyServiceImpl implements IService {
#Autowired
private IDyDBDAO dyDBDAO;
#Override
public void update() {
dyDBDAO.save(getDetailData());
}
#Override
public List<Detail> getCurrentDetail() {
return getDetails(dyDBDAO.findAll());
}
private List<Detail> getDetails(Iterable<Detail> details) {
...blah...
}
private String getPlace(){
Places p = Places.getPlace();//static
return p == null? PlacesUtil.getName("DH"): p.getName;
}
private Detail getDetailData() {
Detail d = new Detail();
d.setName("blah");
d.setDesc("fsdfsdfdsf");
d.setPlace(getPlace());
return d;
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest({Places.class, PlacesUtil.class})
public class MyServiceImplTest {
#InjectMocks
private MyServiceImpl myServiceImpl;
#Mock
private IDyDBDAO dyDBDAO;
#Test
public void testGetCurrentDetail() {
given(dyDBDAO.findAll()).willReturn(getMockDetails());
assertSame(myServiceImpl.getCurrentDetail().size(), 2);
}
#Test
public void testUpdate() {
PowerMockito.mockStatic(Places.class);
// first update , second update -us-west-2 will update
given(Places.getPlace()).willReturn(PlacesUtil.getName("UH"))
.willReturn(null);
myServiceImpl.syncStatus();
// update again with DH
myServiceImpl.syncStatus();
verify(dyDBDAO, times(2)).save(any(Detail.class));
// how to assert checking here
}
private Iterable<Detail> getMockDetails() {
Detail d1 = new Detail();
d1.setName("blah");
d1.setDesc("fsdfsdfdsf");
d1.setPlace("sdfsdf");
Detail d2 = new Detail();
d2.setName("blahblah1");
d2.setDesc("e345345");
d2.setPlace("8907j");
List<Detail> listOfDetail = new ArrayList<>();
listOfDetail.add(eps1);
listOfDetail.add(eps2);
return listOfDetail;
}
}
You need to capture the value passed to the dao save method. Use mockito's ArgumentCaptor for that. Then assert on that value.
Something along these lines:
ArgumentCaptor<Detail> captor = ArgumentCaptor.forClass(Detail.class);
verify(dyDBDAO, times(2)).save(captor.capture());
Detail detail1 = captor.getValues().get(0)
assertEquals(expectedDetail, detail1)
I would assume that your void method that needs to be tested is update in MyServiceImpl.
Firstly, you can verify if dyDBDAO.save() is called.
Mockito.verify(dyDBDAO).save(Mockito.anyList...);
Secondly, you can check the modified or created records in the database by retrieving them and comparing to the inputs from getMockDetails.

Unit test android: How to return function not to be null when calls another function return and use

I have a FileRepository class to fill MutableLiveData. I have two functions in there. One is calling web service and setting list (getAllFilms). Other one is assigning MutableLiveData with first function List (getFilmData). I try to write unit test for MutableLiveData. Can you help me? This function data always comes null.
public class FilmRepositoryTest
#Mock
FilmRepository frepo;
#Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
#Before
public void setUp() throws Exception {
}
#Test
public void getFilmData_forData() throws IOException {
ArrayList<film> filmlistesi = new ArrayList<>();
MutableLiveData<List<film>> bilgi = new MutableLiveData<>();
String arama = "ankara";
filmlistesi.add(new film("Behzat Ç.: Bir Ankara Polisiyesi","2010–2019","tt1795096","series","https://m.media-amazon.com/images/M/MV5BZDZjY2I5ZjEtZGE2MS00ZjRmLTlmMGEtMDQ5ZmZhZWJjYzk3XkEyXkFqcGdeQXVyNDg4MjkzNDk#._V1_SX300.jpg"));
when(frepo.getAllFilms(arama)).thenReturn(filmlistesi);
bilgi.setValue(filmlistesi);
System.out.println(frepo.getFilmData(arama)); // print(NULL)
System.out.println(bilgi.getValue()); // print(filmlistesi)
assertEquals(frepo.getFilmData(arama),bilgi.getValue());
}
public class FilmRepository
public MutableLiveData<List<film>> getFilmData(String a) throws IOException {
MutableLiveData<List<film>> data = new MutableLiveData<>();
data.setValue(getAllFilms(a));
return data;
}
public ArrayList getAllFilms(String filmName) throws IOException {
ArrayList<film> dataset = new ArrayList<>();
return dataset;
}
LiveData or MutableLiveData must have an Observer set of it or else it returns null
Observer<List<film>> observer = new Observer<List<film>>() {
#Override
public void onChanged(#Nullable List<film> films) {
assertEquals(frepo.getFilmData(arama), films.getValue());
biligi.removeObserver(this)
}
};
bilgi.observeForever(observer);
bilgi.setValue(filmlistesi);

Mockito ArgumentCaptor does not return any values on verification

I am trying to use argument capture to determine what arguments are being passed to a mocked Mockito method, but I am not able to capture any values.
class CombinedEvent
{
final List<String> events;
public CombinedEvent() {
this.events = new ArrayList<>();
this.events.add("WATCHITM");
this.events.add("BIDITEM");
}
}
Holder class
class CombinedNotificationAdapter {
private CombinedEvent combinedEvent;
CombinedNotificationAdapter() {
this.combinedEvent = new CombinedEvent();
}
public boolean isEnabled(String user, NotificationPreferenceManager preferenceManager) {
boolean status = true;
for (String event : combinedEvent.events) {
status = status && preferenceManager.isEventEnabled(user, event);
}
return status;
}
}
My unit test
#RunWith(JUnit4.class)
class CombinedNotificationAdapterTest {
private CombinedNotificationAdapter adapter;
#Mock
private NotificationPreferenceManager preferenceManager;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
adapter = new CombinedNotificationAdapter();
}
#Test
public void testIsEnabled() {
doReturn(true).when(preferenceManager).isEventEnabled(eq("test"), anyString());
Assert.assertTrue(adapter.isEnabled("test", preferenceManager));
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(preferenceManager, times(2)).isEventEnabled(eq("test"), captor.capture());
System.out.println(captor.getAllValues());
}
}
The output of captor.getAllValues() is an empty list. I would like the values to return a list of WATCHITM and BIDITEM. I don't know what I am going wrong.
Reference:
https://static.javadoc.io/org.mockito/mockito-core/2.28.2/org/mockito/Mockito.html#15
https://static.javadoc.io/org.mockito/mockito-core/2.6.9/org/mockito/ArgumentCaptor.html
I think you are overdoing:
doReturn(true)
. when(preferenceManager)
.isEventEnabled(eq("test"), anyString()):
You are scrubbing that expected method invocation and then combining that with your argument captor. And that does not work. You can either stub or capture, not both things! See this existing question for example.
My suggestion: look at this answer and learn how to create your own Answer object. Those get passed an instance of InvocationOnMock. And that class allows you to check the arguments passed into the mocked calls, too!

EasyMock am I doing this right?

I'm building a JEE EAR application and I started working with EasyMock to create mocks for the repositories my services are using. But I am not quite sure the result is correct. Two tests in particular where I am testing void methods.
public class VenueServiceTest extends ServiceTest {
private VenueService venueService = new VenueServiceImpl();
private VenueRepository mockVenueRepository; // interface that the service is using
private List<Venue> venues;
private Venue venue1;
private Venue venue2;
#Override
public void setupMock() {
venues = MockUtils.getMockedVenues();
venue1 = venues.get(0);
venue2 = venues.get(1);
mockVenueRepository = createMock(VenueRepository.class);
venueService.setRepository(mockVenueRepository);
}
#Override
public void testUpdate() {
Venue originalVenue = new Venue(0L, "The Venue");
String originalName = originalVenue.getName();
mockVenueRepository.update(originalVenue);
expect(mockVenueRepository.findById(originalVenue.getId())).andReturn(originalVenue);
replay(mockVenueRepository);
originalVenue.setName("Another Venue");
venueService.updateEntity(originalVenue);
Venue newVenue = venueService.getEntity(originalVenue.getId());
String newName = newVenue.getName();
assertFalse("Venue names should not be equal", originalName.equals(newName));
verify(mockVenueRepository);
}
#Override
public void testDelete() {
expect(mockVenueRepository.findById(venue1.getId())).andReturn(venue1);
mockVenueRepository.remove(venue1);
expect(mockVenueRepository.findById(venue1.getId())).andReturn(null);
replay(mockVenueRepository);
assertNotNull(venueService.getEntity(venue1.getId()));
venueService.deleteEntity(venue1);
assertNull(venueService.getEntity(venue1.getId()));
verify(mockVenueRepository);
}
Both of these test passes. But if I comment out the delet/update parts they still pass.
#Override
public void testUpdate() {
Venue originalVenue = new Venue(0L, "The Venue");
String originalName = originalVenue.getName();
// mockVenueRepository.update(originalVenue);
expect(mockVenueRepository.findById(originalVenue.getId())).andReturn(originalVenue);
replay(mockVenueRepository);
originalVenue.setName("Another Venue");
// venueService.updateEntity(originalVenue);
Venue newVenue = venueService.getEntity(originalVenue.getId());
String newName = newVenue.getName();
assertFalse("Venue names should not be equal", originalName.equals(newName));
verify(mockVenueRepository);
}
#Override
public void testDelete() {
expect(mockVenueRepository.findById(venue1.getId())).andReturn(venue1);
// mockVenueRepository.remove(venue1);
expect(mockVenueRepository.findById(venue1.getId())).andReturn(null);
replay(mockVenueRepository);
assertNotNull(venueService.getEntity(venue1.getId()));
// venueService.deleteEntity(venue1);
assertNull(venueService.getEntity(venue1.getId()));
verify(mockVenueRepository);
}
Am I doing this right? My guess is no and if so how do you test this properly?
Thank you!
For the update, you are recording to return originalVenue. Since you are modifying its name, it will indeed be different. There is only one instance of originalVenue through all the test.
For delete, you are recording venue1 and then null. So if you call findById twice, you will receive venue1 and null. The test the delete, you can mock only the remove method to make sure it is called. Calling getEntity makes you test getEntity which is unrelated with the delete.
Basically, to test update and delete, I would do
#Override
public void testUpdate() {
Venue originalVenue = new Venue(0L, "The Venue");
String originalName = originalVenue.getName();
mockVenueRepository.update(originalVenue);
replay(mockVenueRepository);
originalVenue.setName("Another Venue");
venueService.updateEntity(originalVenue);
verify(mockVenueRepository);
}
#Override
public void testDelete() {
mockVenueRepository.remove(venue1);
replay(mockVenueRepository);
venueService.deleteEntity(venue1);
verify(mockVenueRepository);
}

Categories

Resources