Having the following class:
class ToTest{
#Autowired
private Service service;
public String make(){
//do some calcs
obj.setParam(param);
String inverted = service.execute(obj);
return "<" + inverted.toString() + ">";
}
}
I'd like to add a test that asserts me that service.execute is called with an object with the param X.
I'd do that with a verification. I want to mock this call and make it return something testable. I do that with an expectations.
#Tested
ToTest toTest;
#Injected
Service service;
new NonStrictExpectations(){
{
service.exceute((CertainObject)any)
result = "b";
}
};
toTest.make();
new Verifications(){
{
CertainObject obj;
service.exceute(obj = withCapture())
assertEquals("a",obj.getParam());
}
};
I get a null pointer on obj.getParam(). Apparently the verification does not work. If I remove the expectation it works but then I get a null pointer in inverted.toString().
How would you guys make this work?
The following test class is working fine for me, using JMockit 1.4:
public class TempTest
{
static class CertainObject
{
private String param;
String getParam() { return param; }
void setParam(String p) { param = p; }
}
public interface Service { String execute(CertainObject o); }
public static class ToTest
{
private Service service;
public String make()
{
CertainObject obj = new CertainObject();
obj.setParam("a");
String inverted = service.execute(obj);
return "<" + inverted + ">";
}
}
#Tested ToTest toTest;
#Injectable Service service;
#Test
public void temp()
{
new NonStrictExpectations() {{
service.execute((CertainObject) any);
result = "b";
}};
toTest.make();
new Verifications() {{
CertainObject obj;
service.execute(obj = withCapture());
assertEquals("a", obj.getParam());
}};
}
}
Can you show a complete example test which fails?
Related
I have to test DataIdResolver class and it is a class that has a switch case and optional in it. Also there is a one case and default part of switch case that contains each method call. I need to test it and I am not sure how to do it.
public class DataIdResolver {
final DataService dataService;
public DataIdResolver(DataService dataService) {
this.dataService = dataService;
}
public List<String> fetchDataIds(String dataId){
Optional<DataResponse> optionalResponse = dataService.getData(dataId);
if(optionalResponse.isPresent()) {
switch(optionalResponse.get().author){
case "Harry Potter":
return resolveAuthorDataIdAndSiblingsAuthorDataId(optionalResponse.get());
default:
return resolveServerSideDataIdAndSiblingsServerSideDataId(optionalResponse.get());
}
} else {
return List.of(dataId);
}
}
private List<String> resolveAuthorDataIdAndSiblingsAuthorDataId(DataResponse response) {
List<String> resolvedServerSideIds = new ArrayList<>();
resolvedServerSideIds.add(response.serverSideDataId);
if (!response.siblings.isEmpty()){
for (SiblingsDataResponse s : response.siblings) {
resolvedServerSideIds.add(s.dataId);
}
}
return resolvedServerSideIds;
}
}
Here is what I have for start:
public class DataIdResolverTest {
DataService dataService = Mockito.mock(DataService.class);
RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
private final HttpDataService httpDataService = new HttpDataService(restTemplate);
#Test
public void fetchDataIds() {
Optional<DataResponse> optionalResponse = dataService.getData(dataId);
optionalResponse.ifPresent(dataResponse -> Mockito
.when(!dataResponse.siblings.isEmpty()).thenReturn(Boolean.valueOf("siblingsDataId")));
httpDataService.getData("dataIdTest");
}
#Test
public void resolveAuthorDataIdAndSiblingsAuthorDataId(){
}
}
Should I test it all in one test method?
What is the best way to do it?
Any advice appreciated.
Here's example.
public class DataIdResolverTest {
DataService dataService = Mockito.mock(DataService.class);
private final DataIdResolver dataIdResolver = new DataIdResolver(dataService);
#Test
public void fetchDataIds_returnsListWithExceptedString_whenOptionalIsPresent() {
//given
ResponseData responseData = createYourResponseDataHere();
Mockito.when(dataService.getData()).thenReturn(Optional.of(responseData));
//when
List<String> dataIds = dataIdResolver.fetchDataIds();
//then
//here you need to check if your dataIds have expected values, you can use Assertions
//example
Assert.assertEquals("expectedString", dataIds.get(0));
}
#Test
public void fetchDataIds_returnsEmptyList_whenOptionalIsNotPresent() {
//given
ResponseData responseData = createYourResponseDataHere();
Mockito.when(dataService.getData()).thenReturn(Optional.empty());
//when
List<String> dataIds = dataIdResolver.fetchDataIds();
//then
Assert.assertTrue(dataIds.isEmpty());
}
}
In general read more about unit tests. You want test class DataIdResolver but you didn't even create instance of it. You can't test private method without reflection, in general it's bad practice to do it. Also remember to name your test methods better, you can read about it here https://dzone.com/articles/7-popular-unit-test-naming
Hi all i receive Nullpointer when trying to execute this unit test.I want to test e class which receive 3 parameters and returns a string. I think i need to make #Before or something else but it didn't works. Do you have suggestions...Thanks !
public class UrlConstructorTest {
private UrlConstructor urlConstructor;
#Before
public void setUp() {
urlConstructor = new UrlConstructor();
}
public static final String TEST_UPDATE_MANIFEST_SR = "/packages/proxyId/test/test1/123/test3/test_test";
#Test
public void constructUpdateManifestSrInSasTokenTest() {
String result = urlConstructor.composeDeviceRegistrationUrl("test","test123","test");
System.out.println(result);
assertNotNull(result);
assertEquals(TEST, result);
}
}
UrlConstructor is define like this:
#Component
public class UrlConstructor {
And this is the method in this class:
public String composeDUrl(String deviceId, String scopeId) {
return String.format(Constants.socpe, tes, test);
}
In Junit5, you should be using #BeforeEach. Or you can get rid of that setUp method completely.
public class UrlConstructorTest {
private final UrlConstructor urlConstructor = new UrlConstructor();
public static final String TEST_SR = "/packages/proxyId/testID/product/testscope/testcomponent/coomponent_up";
#Test
public void constructTest() {
String result = urlConstructor.composeDeviceRegistrationUrl("testID","coomponent_up","testscope");
System.out.println(result);
assertNotNull(result);
assertEquals(TEST_SR, result);
}
}
Return of method "ContractService" is a return value of method "checkPgwContract". I'm already mock the ContractService class and ContractServiceManager class, but method of checkPgwContract always passed in my unit test.
ContractServiceImpl
#Override
public List getListOfContractBy(String contractNo) {
List<OasysContract> oasysContractList = oasysContractRepository.findByContractNumber(contractNo);
if (!oasysContractList.isEmpty()) {
return oasysContractList;
} else {
List<Contract> pgwContractList = contractRepository.findContractsByContractNumber(contractNo);
if (!pgwContractList.isEmpty()) {
return contractServiceManager.checkPgwContract(pgwContractList);
}
}
return new ArrayList();
}
ContractServiceManagerImpl
private boolean checkHCP(String contractNumber) {
return contractRepository.findContractByExpiredDate(contractNumber) != null ? true : false;
}
private String checkIsFullyPaid(String contractNumber) {
return contractRepository.getFullyPaid(contractNumber);
}
#Override
public List<Contract> checkPgwContract(List<Contract> contractList) {
for (Contract contract : contractList) {
//check paymentType
if (contract.getPaymentType() != null &&
contract.getPaymentType().equals(PAYMENT_TYPE_HCP)) {
if (checkHCP(contract.getContractNumber())) {
//check isFullyPaid
if (checkIsFullyPaid(contract.getContractNumber()).equals(FLAG_YES)) {
return new ArrayList<>();
}
} else {
return new ArrayList<>();
}
}
}
return contractList;
}
UnitTest
#InjectMocks
#Spy
private ContractServiceImpl service;
#Mock
ContractRepository contractRepository;
#Mock
OasysContractRepository oasysContractRepository;
#Mock
ContractServiceManager serviceManager;
public static final String contractNumber = "3900006835";
#Test
public void getListOfContractBy_hcp_success() {
List<OasysContract> oasysContractList = new ArrayList<>();
oasysContractList.isEmpty();
List<Contract> contractList = new ArrayList<>();
contractList.add(BuildUtil.buildContract());
//mock
Mockito.doReturn(oasysContractList).when(oasysContractRepository).findByContractNumber(contractNumber);
Mockito.doReturn(BuildUtil.buildContractList()).when(contractRepository).findContractsByContractNumber(contractNumber);
Mockito.doReturn(contractList).when(serviceManager).checkPgwContract(contractList);
Mockito.doReturn(BuildUtil.buildContract()).when(contractRepository).findContractByExpiredDate(contractNumber);
Mockito.doReturn("N").when(contractRepository).getFullyPaid(contractNumber);
//test
List<Contract> contracts = service.getListOfContractBy(contractNumber);
System.out.println(contracts);
assert(!contracts.isEmpty());
}
Now, the value of contracts parameter is empty. It should be return contractList. I think because mock of method checkPgwContract is ignored.
My test will still pass, which is obviously wrong, so how should I test this?
This line doesn't make sense to me: Mockito.doReturn(contractList).when(serviceManager).checkPgwContract(contractList);
Your method checkPgwContract() won't be called with contractList as parameter so it will not trigger the doReturn from Mockito.
It will be called with whatever BuildUtil.buildContractList() returns in your line above:
Mockito.doReturn(BuildUtil.buildContractList()).when(contractRepository).findContractsByContractNumber(contractNumber);
I have a static method which will be invoking from test method in a class as bellow
public class MyClass
{
private static boolean mockMethod( String input )
{
boolean value;
//do something to value
return value;
}
public static boolean methodToTest()
{
boolean getVal = mockMethod( "input" );
//do something to getVal
return getVal;
}
}
I want to write a test case for method methodToTest by mocking mockMethod.
Tried as bellow and it doesn't give any output
#Before
public void init()
{
Mockit.setUpMock( MyClass.class, MyClassMocked.class );
}
public static class MyClassMocked extends MockUp<MyClass>
{
#Mock
private static boolean mockMethod( String input )
{
return true;
}
}
#Test
public void testMethodToTest()
{
assertTrue( ( MyClass.methodToTest() );
}
To mock your static method:
new MockUp<MyClass>()
{
#Mock
boolean mockMethod( String input ) // no access modifier required
{
return true;
}
};
To mock the static private method:
#Mocked({"mockMethod"})
MyClass myClass;
String result;
#Before
public void init()
{
new Expectations(myClass)
{
{
invoke(MyClass.class, "mockMethod", anyString);
returns(result);
}
}
}
#Test
public void testMethodToTest()
{
result = "true"; // Replace result with what you want to test...
assertTrue( ( MyClass.methodToTest() );
}
From JavaDoc:
Object mockit.Invocations.invoke(Class methodOwner, String methodName, Object... methodArgs)
Specifies an expected invocation to a given static method, with a given list of arguments.
There is another way of mocking static methods using JMockit (using Delegate class). I find it more convenient and elegant.
public class Service {
public String addSuffix(String str) { // method to be tested
return Utils.staticMethod(str);
}
}
public class Utils {
public static String staticMethod(String s) { // method to be mocked
String suffix = DatabaseManager.findSuffix("default_suffix");
return s.concat(suffix);
}
}
public class Test {
#Tested
Service service;
#Mocked
Utils utils; // #Mocked will make sure all methods will be mocked (including static methods)
#Test
public void test() {
new Expectations {{
Utils.staticMethod(anyString); times = 1; result = new Delegate() {
public static String staticMethod(String s) { // should have the same signature (method name and parameters) as Utils#staticMethod
return ""; // provide custom implementation for your Utils#staticMethod
}
}
}}
service.addSuffix("test_value");
new Verifications {{
String s;
Utils.staticMethod(s = withCapture()); times = 1;
assertEquals("test_value", s); // assert that Service#addSuffix propagated "test_value" to Utils#staticMethod
}}
}
}
Reference:
https://jmockit.github.io/tutorial/Mocking.html#delegates
https://jmockit.github.io/tutorial/Mocking.html#withCapture
I have a static method which will be invoking from test method in a class as bellow
public class MyClass
{
private static boolean mockMethod( String input )
{
boolean value;
//do something to value
return value;
}
public static boolean methodToTest()
{
boolean getVal = mockMethod( "input" );
//do something to getVal
return getVal;
}
}
I want to write a test case for method methodToTest by mocking mockMethod.
Tried as bellow and it doesn't give any output
#Before
public void init()
{
Mockit.setUpMock( MyClass.class, MyClassMocked.class );
}
public static class MyClassMocked extends MockUp<MyClass>
{
#Mock
private static boolean mockMethod( String input )
{
return true;
}
}
#Test
public void testMethodToTest()
{
assertTrue( ( MyClass.methodToTest() );
}
To mock your static method:
new MockUp<MyClass>()
{
#Mock
boolean mockMethod( String input ) // no access modifier required
{
return true;
}
};
To mock the static private method:
#Mocked({"mockMethod"})
MyClass myClass;
String result;
#Before
public void init()
{
new Expectations(myClass)
{
{
invoke(MyClass.class, "mockMethod", anyString);
returns(result);
}
}
}
#Test
public void testMethodToTest()
{
result = "true"; // Replace result with what you want to test...
assertTrue( ( MyClass.methodToTest() );
}
From JavaDoc:
Object mockit.Invocations.invoke(Class methodOwner, String methodName, Object... methodArgs)
Specifies an expected invocation to a given static method, with a given list of arguments.
There is another way of mocking static methods using JMockit (using Delegate class). I find it more convenient and elegant.
public class Service {
public String addSuffix(String str) { // method to be tested
return Utils.staticMethod(str);
}
}
public class Utils {
public static String staticMethod(String s) { // method to be mocked
String suffix = DatabaseManager.findSuffix("default_suffix");
return s.concat(suffix);
}
}
public class Test {
#Tested
Service service;
#Mocked
Utils utils; // #Mocked will make sure all methods will be mocked (including static methods)
#Test
public void test() {
new Expectations {{
Utils.staticMethod(anyString); times = 1; result = new Delegate() {
public static String staticMethod(String s) { // should have the same signature (method name and parameters) as Utils#staticMethod
return ""; // provide custom implementation for your Utils#staticMethod
}
}
}}
service.addSuffix("test_value");
new Verifications {{
String s;
Utils.staticMethod(s = withCapture()); times = 1;
assertEquals("test_value", s); // assert that Service#addSuffix propagated "test_value" to Utils#staticMethod
}}
}
}
Reference:
https://jmockit.github.io/tutorial/Mocking.html#delegates
https://jmockit.github.io/tutorial/Mocking.html#withCapture