Unable to mock or bypass static method using Mockito/JMockit/Deencapsulation












0















I am trying add test cases using Mockito. But inside this method, there is a call to a static method which is returning null as per it's logic and I am unable to mock it's behavior as it is a static method. I need to either mock it or bypass it somehow.



I have gone through similar links in stack-overflow, but unable to resolve my problem probably because some of the questioned were asked few years back and the suggested solutions may not fit my question.



I am sharing the code below. Please share your thoughts.



BrandServiceImpl.java



package com.thewatchcompany.modelsdb.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;

@Service("brandService")
public class BrandServiceImpl extends AbstractResourceService<Brand,
BrandRepository> implements BrandService {

private static final Logger LOGGER =
LoggerFactory.getLogger(BrandServiceImpl.class);

@Autowired
public BrandServiceImpl(BrandRepository brandRepository) {
super(brandRepository);
LOGGER.info(" brandRepository : {} ", brandRepository);
}

protected Class<Brand> getResourceType() {
return Brand.class;
}
}


AbstractResourceService.java



Please note that, the test case is failing in this file, where we are setting the Creator using setCreator() and calling the static method getRequestor() from a utility class called ModelsDBUtil.java



package com.thewatchcompany.modelsdb.service;

import static com.thewatchcompany.modelsdb.ModelsDbUtil.getRequestor;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.thewatchcompany.modelsdb.domain.SearchRequest;
import com.thewatchcompany.modelsdb.domain.core.AbstractResource;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.repository.MongoCustomRepository;

public abstract class AbstractResourceService<T extends Resource, R extends
MongoRepository<T, String> & MongoCustomRepository<T>>
implements ResourceService<T> {

private static final Logger LOGGER =
LoggerFactory.getLogger(AbstractResourceService.class);

private final R repository;

public AbstractResourceService(R newRepository) {
this.repository = newRepository;
}

protected abstract Class<T> getResourceType();

protected void validateAdd(T resource) {

}

/** {@inheritDoc} */
public T add(T resource) {

LOGGER.info("Adding resource : {}", resource.getClass().getSimpleName());

validateAdd(resource);

if (resource instanceof AbstractResource) {
((AbstractResource) resource).setCreationInstant(System.currentTimeMillis()).setCreator(getRequestor());
} else {
LOGGER.warn("Invalid resource type: {}", resource.getClass().getName());
}

return repository.save(resource);
}
}


ModelsDbUtil.java



package com.thewatchcompany.modelsdb;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.service.ResourceService;

public final class ModelsDbUtil {

private ModelsDbUtil() {
// Prohibit instantiation
}

public static String getRequestor() {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
}
return null;
}
}


Finally, the test class:



package com.thewatchcompany.modelsdb.service;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.thewatchcompany.modelsdb.ModelsDbUtil;
import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;
import mockit.MockUp;

// @RunWith(PowerMockRunner.class)
// @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
// @PrepareForTest(ModelsDbUtil.class)
// @RunWith(JMockit.class)
@RunWith(SpringRunner.class)
@SpringBootTest
public class BrandServiceTest {

@MockBean
private BrandRepository brandRepository;

@Autowired
private BrandService brandService;

private Brand brand;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);

brand = new Brand();
brand.setId("001");
brand.setName("Panerai");
brand.setDescription("Panerai watches");
brand.setActive(true);
}

@Test
public void testAdd() {

when(brandRepository.save(ArgumentMatchers.any(Brand.class)))
.thenReturn(brand);

// final ModelsDbUtil handler2 = spy(ModelsDbUtil.class);
// doReturn("").when(handler2).getRequestor();

// doReturn("").when(modelsDBUtil.getRequestor());
// when(ModelsDbUtil.getRequestor()).thenReturn("");

// final AbstractResource handler = spy(AbstractResource.class);
// Mockito.ignoreStubs(handler.setCreator(ArgumentMatchers.anyString()));

// new MockUp<ModelsDbUtil>() {
// @mockit.Mock
// String getRequestor() {
// return "dssd";
// }
// };

//final String user = Deencapsulation.invoke(ModelsDbUtil.class, "getRequestor"); //Null-pointer exception
//assertEquals("user", user);

final Brand savedBrand = brandService.add(brand);
assertEquals(savedBrand, brand);
}
}









share|improve this question

























  • You can mock final class or static method with PowerMock but not with Mockito. But show us you test where you can not do your mock , maybe we can find some way to bypass it

    – TinyOS
    Nov 26 '18 at 15:24











  • getRequestor() has no parameters, so why are you invoking it with an empty string?

    – Rogério
    Nov 26 '18 at 16:22











  • @Rogério, Yes you are correct. I was only trying to see how does the invoke() method behave when I pass the empty string. Ideally, it should be without the string param, but the line wouldn't work for me anyway as it will throw null-pointer exception from the SecurityContextHolder. I need a way to either bypass it or mock it's behavior to pass my own object.

    – Kishor .M
    Nov 26 '18 at 19:42











  • @TinyOS, Thanks for responding, but is it possible to use PowerMock and Mockito in one test class? I am not really interested in the static methods. I only want to get rid of that one line where its calling the static method and creating a lot of problems for the normal execution of my test methods.

    – Kishor .M
    Nov 26 '18 at 19:48
















0















I am trying add test cases using Mockito. But inside this method, there is a call to a static method which is returning null as per it's logic and I am unable to mock it's behavior as it is a static method. I need to either mock it or bypass it somehow.



I have gone through similar links in stack-overflow, but unable to resolve my problem probably because some of the questioned were asked few years back and the suggested solutions may not fit my question.



I am sharing the code below. Please share your thoughts.



BrandServiceImpl.java



package com.thewatchcompany.modelsdb.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;

@Service("brandService")
public class BrandServiceImpl extends AbstractResourceService<Brand,
BrandRepository> implements BrandService {

private static final Logger LOGGER =
LoggerFactory.getLogger(BrandServiceImpl.class);

@Autowired
public BrandServiceImpl(BrandRepository brandRepository) {
super(brandRepository);
LOGGER.info(" brandRepository : {} ", brandRepository);
}

protected Class<Brand> getResourceType() {
return Brand.class;
}
}


AbstractResourceService.java



Please note that, the test case is failing in this file, where we are setting the Creator using setCreator() and calling the static method getRequestor() from a utility class called ModelsDBUtil.java



package com.thewatchcompany.modelsdb.service;

import static com.thewatchcompany.modelsdb.ModelsDbUtil.getRequestor;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.thewatchcompany.modelsdb.domain.SearchRequest;
import com.thewatchcompany.modelsdb.domain.core.AbstractResource;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.repository.MongoCustomRepository;

public abstract class AbstractResourceService<T extends Resource, R extends
MongoRepository<T, String> & MongoCustomRepository<T>>
implements ResourceService<T> {

private static final Logger LOGGER =
LoggerFactory.getLogger(AbstractResourceService.class);

private final R repository;

public AbstractResourceService(R newRepository) {
this.repository = newRepository;
}

protected abstract Class<T> getResourceType();

protected void validateAdd(T resource) {

}

/** {@inheritDoc} */
public T add(T resource) {

LOGGER.info("Adding resource : {}", resource.getClass().getSimpleName());

validateAdd(resource);

if (resource instanceof AbstractResource) {
((AbstractResource) resource).setCreationInstant(System.currentTimeMillis()).setCreator(getRequestor());
} else {
LOGGER.warn("Invalid resource type: {}", resource.getClass().getName());
}

return repository.save(resource);
}
}


ModelsDbUtil.java



package com.thewatchcompany.modelsdb;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.service.ResourceService;

public final class ModelsDbUtil {

private ModelsDbUtil() {
// Prohibit instantiation
}

public static String getRequestor() {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
}
return null;
}
}


Finally, the test class:



package com.thewatchcompany.modelsdb.service;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.thewatchcompany.modelsdb.ModelsDbUtil;
import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;
import mockit.MockUp;

// @RunWith(PowerMockRunner.class)
// @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
// @PrepareForTest(ModelsDbUtil.class)
// @RunWith(JMockit.class)
@RunWith(SpringRunner.class)
@SpringBootTest
public class BrandServiceTest {

@MockBean
private BrandRepository brandRepository;

@Autowired
private BrandService brandService;

private Brand brand;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);

brand = new Brand();
brand.setId("001");
brand.setName("Panerai");
brand.setDescription("Panerai watches");
brand.setActive(true);
}

@Test
public void testAdd() {

when(brandRepository.save(ArgumentMatchers.any(Brand.class)))
.thenReturn(brand);

// final ModelsDbUtil handler2 = spy(ModelsDbUtil.class);
// doReturn("").when(handler2).getRequestor();

// doReturn("").when(modelsDBUtil.getRequestor());
// when(ModelsDbUtil.getRequestor()).thenReturn("");

// final AbstractResource handler = spy(AbstractResource.class);
// Mockito.ignoreStubs(handler.setCreator(ArgumentMatchers.anyString()));

// new MockUp<ModelsDbUtil>() {
// @mockit.Mock
// String getRequestor() {
// return "dssd";
// }
// };

//final String user = Deencapsulation.invoke(ModelsDbUtil.class, "getRequestor"); //Null-pointer exception
//assertEquals("user", user);

final Brand savedBrand = brandService.add(brand);
assertEquals(savedBrand, brand);
}
}









share|improve this question

























  • You can mock final class or static method with PowerMock but not with Mockito. But show us you test where you can not do your mock , maybe we can find some way to bypass it

    – TinyOS
    Nov 26 '18 at 15:24











  • getRequestor() has no parameters, so why are you invoking it with an empty string?

    – Rogério
    Nov 26 '18 at 16:22











  • @Rogério, Yes you are correct. I was only trying to see how does the invoke() method behave when I pass the empty string. Ideally, it should be without the string param, but the line wouldn't work for me anyway as it will throw null-pointer exception from the SecurityContextHolder. I need a way to either bypass it or mock it's behavior to pass my own object.

    – Kishor .M
    Nov 26 '18 at 19:42











  • @TinyOS, Thanks for responding, but is it possible to use PowerMock and Mockito in one test class? I am not really interested in the static methods. I only want to get rid of that one line where its calling the static method and creating a lot of problems for the normal execution of my test methods.

    – Kishor .M
    Nov 26 '18 at 19:48














0












0








0








I am trying add test cases using Mockito. But inside this method, there is a call to a static method which is returning null as per it's logic and I am unable to mock it's behavior as it is a static method. I need to either mock it or bypass it somehow.



I have gone through similar links in stack-overflow, but unable to resolve my problem probably because some of the questioned were asked few years back and the suggested solutions may not fit my question.



I am sharing the code below. Please share your thoughts.



BrandServiceImpl.java



package com.thewatchcompany.modelsdb.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;

@Service("brandService")
public class BrandServiceImpl extends AbstractResourceService<Brand,
BrandRepository> implements BrandService {

private static final Logger LOGGER =
LoggerFactory.getLogger(BrandServiceImpl.class);

@Autowired
public BrandServiceImpl(BrandRepository brandRepository) {
super(brandRepository);
LOGGER.info(" brandRepository : {} ", brandRepository);
}

protected Class<Brand> getResourceType() {
return Brand.class;
}
}


AbstractResourceService.java



Please note that, the test case is failing in this file, where we are setting the Creator using setCreator() and calling the static method getRequestor() from a utility class called ModelsDBUtil.java



package com.thewatchcompany.modelsdb.service;

import static com.thewatchcompany.modelsdb.ModelsDbUtil.getRequestor;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.thewatchcompany.modelsdb.domain.SearchRequest;
import com.thewatchcompany.modelsdb.domain.core.AbstractResource;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.repository.MongoCustomRepository;

public abstract class AbstractResourceService<T extends Resource, R extends
MongoRepository<T, String> & MongoCustomRepository<T>>
implements ResourceService<T> {

private static final Logger LOGGER =
LoggerFactory.getLogger(AbstractResourceService.class);

private final R repository;

public AbstractResourceService(R newRepository) {
this.repository = newRepository;
}

protected abstract Class<T> getResourceType();

protected void validateAdd(T resource) {

}

/** {@inheritDoc} */
public T add(T resource) {

LOGGER.info("Adding resource : {}", resource.getClass().getSimpleName());

validateAdd(resource);

if (resource instanceof AbstractResource) {
((AbstractResource) resource).setCreationInstant(System.currentTimeMillis()).setCreator(getRequestor());
} else {
LOGGER.warn("Invalid resource type: {}", resource.getClass().getName());
}

return repository.save(resource);
}
}


ModelsDbUtil.java



package com.thewatchcompany.modelsdb;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.service.ResourceService;

public final class ModelsDbUtil {

private ModelsDbUtil() {
// Prohibit instantiation
}

public static String getRequestor() {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
}
return null;
}
}


Finally, the test class:



package com.thewatchcompany.modelsdb.service;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.thewatchcompany.modelsdb.ModelsDbUtil;
import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;
import mockit.MockUp;

// @RunWith(PowerMockRunner.class)
// @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
// @PrepareForTest(ModelsDbUtil.class)
// @RunWith(JMockit.class)
@RunWith(SpringRunner.class)
@SpringBootTest
public class BrandServiceTest {

@MockBean
private BrandRepository brandRepository;

@Autowired
private BrandService brandService;

private Brand brand;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);

brand = new Brand();
brand.setId("001");
brand.setName("Panerai");
brand.setDescription("Panerai watches");
brand.setActive(true);
}

@Test
public void testAdd() {

when(brandRepository.save(ArgumentMatchers.any(Brand.class)))
.thenReturn(brand);

// final ModelsDbUtil handler2 = spy(ModelsDbUtil.class);
// doReturn("").when(handler2).getRequestor();

// doReturn("").when(modelsDBUtil.getRequestor());
// when(ModelsDbUtil.getRequestor()).thenReturn("");

// final AbstractResource handler = spy(AbstractResource.class);
// Mockito.ignoreStubs(handler.setCreator(ArgumentMatchers.anyString()));

// new MockUp<ModelsDbUtil>() {
// @mockit.Mock
// String getRequestor() {
// return "dssd";
// }
// };

//final String user = Deencapsulation.invoke(ModelsDbUtil.class, "getRequestor"); //Null-pointer exception
//assertEquals("user", user);

final Brand savedBrand = brandService.add(brand);
assertEquals(savedBrand, brand);
}
}









share|improve this question
















I am trying add test cases using Mockito. But inside this method, there is a call to a static method which is returning null as per it's logic and I am unable to mock it's behavior as it is a static method. I need to either mock it or bypass it somehow.



I have gone through similar links in stack-overflow, but unable to resolve my problem probably because some of the questioned were asked few years back and the suggested solutions may not fit my question.



I am sharing the code below. Please share your thoughts.



BrandServiceImpl.java



package com.thewatchcompany.modelsdb.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;

@Service("brandService")
public class BrandServiceImpl extends AbstractResourceService<Brand,
BrandRepository> implements BrandService {

private static final Logger LOGGER =
LoggerFactory.getLogger(BrandServiceImpl.class);

@Autowired
public BrandServiceImpl(BrandRepository brandRepository) {
super(brandRepository);
LOGGER.info(" brandRepository : {} ", brandRepository);
}

protected Class<Brand> getResourceType() {
return Brand.class;
}
}


AbstractResourceService.java



Please note that, the test case is failing in this file, where we are setting the Creator using setCreator() and calling the static method getRequestor() from a utility class called ModelsDBUtil.java



package com.thewatchcompany.modelsdb.service;

import static com.thewatchcompany.modelsdb.ModelsDbUtil.getRequestor;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.repository.MongoRepository;

import com.thewatchcompany.modelsdb.domain.SearchRequest;
import com.thewatchcompany.modelsdb.domain.core.AbstractResource;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.repository.MongoCustomRepository;

public abstract class AbstractResourceService<T extends Resource, R extends
MongoRepository<T, String> & MongoCustomRepository<T>>
implements ResourceService<T> {

private static final Logger LOGGER =
LoggerFactory.getLogger(AbstractResourceService.class);

private final R repository;

public AbstractResourceService(R newRepository) {
this.repository = newRepository;
}

protected abstract Class<T> getResourceType();

protected void validateAdd(T resource) {

}

/** {@inheritDoc} */
public T add(T resource) {

LOGGER.info("Adding resource : {}", resource.getClass().getSimpleName());

validateAdd(resource);

if (resource instanceof AbstractResource) {
((AbstractResource) resource).setCreationInstant(System.currentTimeMillis()).setCreator(getRequestor());
} else {
LOGGER.warn("Invalid resource type: {}", resource.getClass().getName());
}

return repository.save(resource);
}
}


ModelsDbUtil.java



package com.thewatchcompany.modelsdb;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import com.thewatchcompany.modelsdb.domain.core.Resource;
import com.thewatchcompany.modelsdb.exception.ResourceNotFoundException;
import com.thewatchcompany.modelsdb.service.ResourceService;

public final class ModelsDbUtil {

private ModelsDbUtil() {
// Prohibit instantiation
}

public static String getRequestor() {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
return ((UserDetails) principal).getUsername();
}
return null;
}
}


Finally, the test class:



package com.thewatchcompany.modelsdb.service;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.thewatchcompany.modelsdb.ModelsDbUtil;
import com.thewatchcompany.modelsdb.domain.core.Brand;
import com.thewatchcompany.modelsdb.repository.BrandRepository;
import mockit.MockUp;

// @RunWith(PowerMockRunner.class)
// @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
// @PrepareForTest(ModelsDbUtil.class)
// @RunWith(JMockit.class)
@RunWith(SpringRunner.class)
@SpringBootTest
public class BrandServiceTest {

@MockBean
private BrandRepository brandRepository;

@Autowired
private BrandService brandService;

private Brand brand;

@Before
public void setup() {
MockitoAnnotations.initMocks(this);

brand = new Brand();
brand.setId("001");
brand.setName("Panerai");
brand.setDescription("Panerai watches");
brand.setActive(true);
}

@Test
public void testAdd() {

when(brandRepository.save(ArgumentMatchers.any(Brand.class)))
.thenReturn(brand);

// final ModelsDbUtil handler2 = spy(ModelsDbUtil.class);
// doReturn("").when(handler2).getRequestor();

// doReturn("").when(modelsDBUtil.getRequestor());
// when(ModelsDbUtil.getRequestor()).thenReturn("");

// final AbstractResource handler = spy(AbstractResource.class);
// Mockito.ignoreStubs(handler.setCreator(ArgumentMatchers.anyString()));

// new MockUp<ModelsDbUtil>() {
// @mockit.Mock
// String getRequestor() {
// return "dssd";
// }
// };

//final String user = Deencapsulation.invoke(ModelsDbUtil.class, "getRequestor"); //Null-pointer exception
//assertEquals("user", user);

final Brand savedBrand = brandService.add(brand);
assertEquals(savedBrand, brand);
}
}






spring-boot junit mockito junit4 jmockit






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 19:44







Kishor .M

















asked Nov 26 '18 at 13:49









Kishor .MKishor .M

5116




5116













  • You can mock final class or static method with PowerMock but not with Mockito. But show us you test where you can not do your mock , maybe we can find some way to bypass it

    – TinyOS
    Nov 26 '18 at 15:24











  • getRequestor() has no parameters, so why are you invoking it with an empty string?

    – Rogério
    Nov 26 '18 at 16:22











  • @Rogério, Yes you are correct. I was only trying to see how does the invoke() method behave when I pass the empty string. Ideally, it should be without the string param, but the line wouldn't work for me anyway as it will throw null-pointer exception from the SecurityContextHolder. I need a way to either bypass it or mock it's behavior to pass my own object.

    – Kishor .M
    Nov 26 '18 at 19:42











  • @TinyOS, Thanks for responding, but is it possible to use PowerMock and Mockito in one test class? I am not really interested in the static methods. I only want to get rid of that one line where its calling the static method and creating a lot of problems for the normal execution of my test methods.

    – Kishor .M
    Nov 26 '18 at 19:48



















  • You can mock final class or static method with PowerMock but not with Mockito. But show us you test where you can not do your mock , maybe we can find some way to bypass it

    – TinyOS
    Nov 26 '18 at 15:24











  • getRequestor() has no parameters, so why are you invoking it with an empty string?

    – Rogério
    Nov 26 '18 at 16:22











  • @Rogério, Yes you are correct. I was only trying to see how does the invoke() method behave when I pass the empty string. Ideally, it should be without the string param, but the line wouldn't work for me anyway as it will throw null-pointer exception from the SecurityContextHolder. I need a way to either bypass it or mock it's behavior to pass my own object.

    – Kishor .M
    Nov 26 '18 at 19:42











  • @TinyOS, Thanks for responding, but is it possible to use PowerMock and Mockito in one test class? I am not really interested in the static methods. I only want to get rid of that one line where its calling the static method and creating a lot of problems for the normal execution of my test methods.

    – Kishor .M
    Nov 26 '18 at 19:48

















You can mock final class or static method with PowerMock but not with Mockito. But show us you test where you can not do your mock , maybe we can find some way to bypass it

– TinyOS
Nov 26 '18 at 15:24





You can mock final class or static method with PowerMock but not with Mockito. But show us you test where you can not do your mock , maybe we can find some way to bypass it

– TinyOS
Nov 26 '18 at 15:24













getRequestor() has no parameters, so why are you invoking it with an empty string?

– Rogério
Nov 26 '18 at 16:22





getRequestor() has no parameters, so why are you invoking it with an empty string?

– Rogério
Nov 26 '18 at 16:22













@Rogério, Yes you are correct. I was only trying to see how does the invoke() method behave when I pass the empty string. Ideally, it should be without the string param, but the line wouldn't work for me anyway as it will throw null-pointer exception from the SecurityContextHolder. I need a way to either bypass it or mock it's behavior to pass my own object.

– Kishor .M
Nov 26 '18 at 19:42





@Rogério, Yes you are correct. I was only trying to see how does the invoke() method behave when I pass the empty string. Ideally, it should be without the string param, but the line wouldn't work for me anyway as it will throw null-pointer exception from the SecurityContextHolder. I need a way to either bypass it or mock it's behavior to pass my own object.

– Kishor .M
Nov 26 '18 at 19:42













@TinyOS, Thanks for responding, but is it possible to use PowerMock and Mockito in one test class? I am not really interested in the static methods. I only want to get rid of that one line where its calling the static method and creating a lot of problems for the normal execution of my test methods.

– Kishor .M
Nov 26 '18 at 19:48





@TinyOS, Thanks for responding, but is it possible to use PowerMock and Mockito in one test class? I am not really interested in the static methods. I only want to get rid of that one line where its calling the static method and creating a lot of problems for the normal execution of my test methods.

– Kishor .M
Nov 26 '18 at 19:48












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53482539%2funable-to-mock-or-bypass-static-method-using-mockito-jmockit-deencapsulation%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53482539%2funable-to-mock-or-bypass-static-method-using-mockito-jmockit-deencapsulation%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)