J Unit Test Case Did not give coverage even when passed - spring

i am writing test case for partial update or Patch call service method.
but i am having problem that the Unit test passes but it is not giving the coverage.
and also it is giving coverage to the methods inside this function.
the test case i have written is as follow
#MockitoSettings(strictness = Strictness.LENIENT)
#Test
public void updateProductPartialTest() throws Exception {
Product prod = saveprod();
ProductDto dto = saveDto();
PartialProductDto updto = patchDto();
Product upprod = upprod();
ProductDto updtoo = updateDto();
String id = "5e7e2fcf-c0b8-4c9b-860b-55d71a3c580f";
given(mapper.ProductDtotoProduct(dto)).willReturn(prod);
given(mapper.ProductToProductDto(prod)).willReturn(dto);
given(productrepository.findByProductId(dto.getProductId())).willReturn(Optional.empty());
given(productrepository.save(prod)).willReturn(prod);
service.addProduct(dto);
given(productrepository.findByProductId(dto.getProductId())).willReturn(Optional.of(prod));
given(service.mappingForPatrialUpdate(updto, prod)).willReturn(upprod);
Mockito.doReturn(updtoo).when(service).updateProductPartial(updto, id);
given(mapper.ProductToProductDto(prod)).willReturn(dto);
given(mapper.ProductDtotoProduct(dto)).willReturn(prod);
given(service.addProduct(dto)).willReturn(dto);
service.addProduct(dto);
service.updateProductPartial(updto, id);
given(productrepository.findByProductId(id)).willReturn(Optional.of(upprod));
assertThat(productrepository.findByProductId(id).get().equals(upprod));
}
and the things that i am mocking are :
#Mock
ProductRepository productrepository;
#Mock
SimpleProductdtoProductMapper mapper;
#Spy
#InjectMocks
ProductServiceImpl service;
#InjectMocks
ProductGetServiceImpl serviceget;
As far as i understand is this issue is caused by following line:
Mockito.doReturn(updtoo).when(service).updateProductPartial(updto, id);
what can i replace this line with so i get coverage to these test.
any help or suggestion is appreciated.

Related

SonarQube doesn't recognize Mapper's unit test

Running SonarQube Version 6.7.2 (build 37468) - LGPL v3, Junit 4 and mockito in our project, I noted that SonarQube does not recognize Mapper's unit test and decrease the project's percentual. In my local enviroment, the test works well and the coverage is 100% by Eclipse.
Below is the UT code:
#RunWith(MockitoJUnitRunner.class)
public class ClassMapperTest {
#Mock
private ClassMapper mapper;
#Mock
private ClassDTO dto;
#Before
public void setUp() {
mapper = Mockito.mock(ClassMapper.class);
dto = Mockito.mock(ClassDTO.class);
}
#Test
public void returnResource() {
Mockito.when(mapper.fromMethod(Mockito.anySet())).thenReturn(new HashSet<>());
mapper.fromMethod(new HashSet<ClassDTO>());
}
The statistics:
After Commit:
Does anyone have any idea?
Sonarqube is right with the computation. You do have a major issue within your test, the code you seem to be testing is mocked aka you are not testing the actual code, but a fake of it.
When you mock a class you create a dummy fake version of this class, which does not have any implementation (mapper = Mockito.mock(ClassMapper.class);).
you then tell your mock to return a value when a method is called Mockito.when(mapper.fromMethod(Mockito.anySet())).thenReturn(new HashSet<>());. This way you are actually not testing your fromMethod, you just testing a method, which you told in your test what to return.
A proper test would look something like this:
#RunWith(MockitoJUnitRunner.class)
public class ClassMapperTest {
private ClassMapper mapper;
#Mock
private ClassDTO dto;
#Before
public void setUp() {
mapper = new ClassMapper();
// no need to do that, MockitoJUnitRunner is doing this for you
// dto = Mockito.mock(ClassDTO.class);
}
#Test
public void returnResource() {
// calling the actual method
assertTrue(mapper.fromMethod(new HashSet<ClassDTO>()) != null);
}
}
There is also no need for the dto as it is not used within your test at all, but I left it in there, to mark the unnecessary mock instantiation, which is done by the MockitoJUnitRunner.
// Disclaimer: I am not guaranteeing that your tests will pass, with my suggestion, I only want to highlight the problem with the test.

Spring boot with Mockito mocking NamedParameterJdbcTemplate

Trying to unit test a method which is defined as :
public void myMethod(List<? extends MyModel> model){
int[] result = namedParameterJdbcTemplate.batchUpdate("update query", SqlParameterSourceUtils.createBatch(model));
}
In my test class i am defining test method as
class MyTestClass{
#Mock
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
#InjectMocks
MyDao dao;
#Test
public void testMyMethod() {
final int[] rowsAffected = new int[]{1,2};
when(namedParameterJdbcTemplate.batchUpdate(any(), SqlParameterSourceUtils.createBatch(Arrays.asList(anySet())))).thenReturn(rowsAffected);
List<MyModel> myModels = new ArrayList<>();
MyModel mymodel = new MyModel();
mymodel.setSomeParam("");
myModels.add(mymodel);
dao.myMethod(myModels);
}
}
While running this test method , i am getting NullPointerException in called method(myMethod()). int[] result is coming as null. My understanding is it should get the result from the stub in the mock.
Please help me understand what am i doing wrong.
It seems that you're not using the correct import for any() because if it would be the correct ArgumentMatchers.any() from Mockito, Mockito would complain that you don't use an ArgumentMatcher for both parameters of .batchUpdate().
You can statically import it with import static org.mockito.ArgumentMatchers.*; or use ArgumentMatchers.any().
So as first step, try the following:
when(namedParameterJdbcTemplate.batchUpdate(ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(rowsAffected);
or be less generic and match the return type of SqlParameterSourceUtils.createBatch() with:
// I don't know what SqlParameterSourceUtils.createBatch() returns, so you might have to adjust it
when(namedParameterJdbcTemplate.batchUpdate(ArgumentMatchers.any(), ArgumentMatchers.eq("SOME RETURN"))).thenReturn(rowsAffected);
It worked by adding the cast to the Argument matchers:
Updated Code :
when(namedParameterJdbcTemplate.batchUpdate(anyString(), (SqlParameterSource[]) any())).thenReturn(rowsAffected);

how to write Test case for if else using mockMvc in spring boot

How can i write Mockmvc test case for below code:
My controller class
#RestController
public class CartController {
#Autowired
private CartService cartService;
#GetMapping(path = "/addToCart", produces = MediaType.APPLICATION_JSON_VALUE)
public String cart(#Valid #RequestBody Cart cart) {
return cartService.cart(cart);
}
}
My CartService class:
#Service
public class CartService {
private LoginRepository loginRepository;
#Autowired
private ProductRepository productRepository;
#Autowired
private CartRepository cartRepository;
#Autowired
private EmailService emailService;
public CartService(LoginRepository loginRepository) {
this.loginRepository = loginRepository;
}
public String cart(Cart cart) {
String username = cart.getUserName();
System.out.println(username);
String password = cart.getPassword();
String email = cart.getEmail();
if (loginRepository.existsByUserNameAndPassword(username, password)) {
String productname = cart.getProductName();
System.out.println(productname);
String price = cart.getPrice();
String discription = cart.getDiscription();
if (productname != null) {
if (productRepository.existsByProductNameAndPriceAndDiscription(productname, price, discription)) {
Integer count = cartRepository.countByUserName(username);
System.out.println(count);
cartRepository.save(new Cart(username, password, email, productname, price, discription, count));
return "{\"message\":\"product Successfully added to cart\"}";
} else {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);
}
} else {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
}
} else {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}
I don't know how to write test case for above code using mockmvc. i don't know how can i write mockmvc test case for if else statement. so please help me how to write mockmvc test case for entire code so that i can do mockmvc test for if else statment also.
I think you have a misunderstanding of what #WebMvcTest is used for.
It is for Integration Testing a single slice of your Application – namely Web MVC.
This means that your #WebMvcTest annotated Test should only use Mocks of your Service because what they should test is all the Web related stuff (proper conversion to JSON, XML; returning correct response codes, etc)
There is a tutorial on spring.io which should answer your questions.
For Testing your Service you can use plain old Unit Test with for example JUnit.
In order for that to work you need to do some rework on your classes. First thing I would suggest is to replace the field injections with constructor injection. This is the recommended way of injection. Read here for more information.
After this change you can mock the dependencies of your Service (for example with Mockito) and pass them via the constructor.
This way you can test the different if/else branches in your code.
And last but not least I would highly recommend to do some other rework on your service. Currently it returns information that are highly coupled to the Web context(the manually crafted JSON, the ResponseStatusException). The handling of those is the responsibility of your controller. Your Service should be independent of the thing (the controller in your case) that uses it. Just imagine your Service will be used by a other Class for a CLI Tool which does know nothing about JSON and response statuses.

Mockito mock CassandraOperation Slice method

I am using the Mockito framework to write the mock Junit test cases below is my Service class to test the Junit test code
public class UserService {
#Autowired
private CassandraOperations template
public UserDTO getUserDTO(String date, String pagingState) {
Select select = QueryBuilder.select().all()
.from("tbl_user");
select.where(QueryBuilder.eq(date, date));
select.setFetchSize(30);
if (pagingState != null) {
select.setPagingState(PagingState.fromString(pagingState));
}
Slice<UserDTO> usgerDTO = template.slice(select, UserDTO.class);
if(usgerDTO.hasNext()) {
}
return usgerDTO.get();
}
Test case Class is writted
#RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
#InjectMocks
private UserService service ;
#Mock
private CassandraOperations template;
#Mock
private UserDTO userDTO;
private String date= "2019-09";
#Test(expected = Exception.class)
public void test() {
Slice<UserDTO> userDTO= Mockito.mock(Slice.class);
Select select = Mockito.mock(Select.class);
Mockito.when(template.slice(select, UserDTO.class)).thenReturn(userDTO);
metricReportDTO = service.getUserDTO(date, null);
}
}
I am getting Null values on this line
Slice<UserDTO> usgerDTO = template.slice(select, UserDTO.class);
Can you please helm me how to test template.slice method
Note: I should not use the PowerMockito
Your code snippet doesn't make sense in that you call service.getMetricsReports(date, null) in your test but your UserService code example only has the method getUserDTO. Assuming that is just a typo then you need to use matchers to get the mock to work in your when.
Mockito.when(template.slice(any(Select.class), eq(UserDTO.class))).thenReturn(userDTO);
This means whenever the first param is a class of type Select and the second is equal to UserDTO.class then return the userDTO if those 2 params don't match those conditions it will return null.
You can also make it match the exact Select assuming it has an overridden equals method. In the case where you send a null pagingState then something like:
Select stubSelect = QueryBuilder.select().all()
.from("tbl_user");
stubSelect.where(QueryBuilder.eq(date, date));
stubSelect.setFetchSize(30);
Mockito.when(template.slice(eq(stubSelect), eq(UserDTO.class))).thenReturn(userDTO);

Exception while getting values from Mocked object using Mockito

I am writing junit using mockito for a Spring #component class.
When it try to access the static field from final constant file throwing Null pointer exception.
CruserDomainTest
#RunWith(MockitoJUnitRunner.class)
public class CruserTest {
#InjectMocks
CruserDomain eDomain = new CruserDomain();
#Test
public void testGetCruseById() throws Exception,
{
String cCode = "AA";
int employeeId = 21305;
when(
cruseRepository.getTestId(
anyString(), anyInt())).thenReturn(
buildAndReturnList());
when(
payDomain.getRefPay(anyString(),
anyString(), anyString(), anyString()))
.thenReturn(buildPay());
CruseMember expectedResponse = eDomain.getMemberById(
airlineCode, employeeId);
}
CruserDomain
//getting null pointer exception in the below line execution
//while getting the current month
public CruseMember getMemberById(String cCode, int employeeId)
throws Exception {
//Some code //
if (contractMonth.getType().equals(
CruseConstant.CURRENT_MONTH)) {
currentMonthStartDate = cMonth.getStartDate();
} else if (contractMonth.getType().equals(
CruseConstant.OTHER_MONTH)) {
nextMonthStartDate = cMonth.getStartDate();
}
CruseConstant:
public final class CruseConstant {
public static final String CURRENT_MONTH = "C";
public static final String OTHER_MONTH = "O";
}
I tried with ReflectionTestutils but throwing exception while junit starts.
Help me on how to lookup final class static variables in the injectMocked class.
I strongly advise you to not mock domain objects, instead I would craft builders that can generate those objects.
Also in the code snippet #InjectMocks has no mock to inject, so injects nothing, mock fields should be declared in the test class. However I stress the point of not mocking the domain !
We've written this page on how to write good tests, I think TDD practitioners should read it, wether they use mockito or not. Lot of people contributed to refine this wiki page.
=> https://github.com/mockito/mockito/wiki/How-to-write-good-tests
It is really hard to understand your code because you have replaced the interesting parts with comments, but I would guess that you get a NPE because
contractMonth
is null. That is because you did not mock and/or forgot to define the behaviour of the class that you get the contractMonth from (CruserRepository?)

Resources