I am currently doing a small project on spring-mvc in my backend and I am trying to create tests for my converters and engines. Below is my BookmarkEngine.java file
#Service
public class BookmarkEngine implements IBookmarkEngine{
private static final String URL_PREFIX = "http://";
#Override
public String getFullUrl(String url) {
if(!url.startsWith(URL_PREFIX))
{
return URL_PREFIX + url;
}
return url;
}
}
How would I go about writing a test for this?
Here is my BookmarkEngineTest:
public class BookmarkEngineTest {
IBookmarkEngine bookmarkEngine = new BookmarkEngine();
private ViewBookmark defaultBookmark;
#Before
public void setUp() throws Exception {
defaultBookmark = new ViewBookmark();
defaultBookmark.setBookmarkId(1L);
defaultBookmark.setTitle("A sample bookmark");
defaultBookmark.setUrl("This is a sample bookmark.");
defaultBookmark.setAuthor(".");
defaultBookmark.setLastUpdated(1497812309081L);
}
#Test
public void getFullUrl() {
String result = bookmarkEngine.getFullUrl(defaultBookmark.getUrl());
assertThat(result.length(), is(defaultBookmark.getUrl().length()));
}
}
That certain test in getFullUrl() does not run, but how can I can make it work?
You can make a test to see if the strings will match such as
#Test
public void getFullUrl() {
String testurl = "facebook.com";
String testurl2 = "http://facebook.com";
assertEquals(bookmarkEngine.getFullUrl(testurl),"http://facebook.com");
assertEquals(bookmarkEngine.getFullUrl(testurl2),"http://facebook.com");
}
Related
Hello Team,
I recently tried reading contents from application.yml file in a Spring Boot project (Version 2.3.4).
Initially, all the properties from yml file were getting read as null.
After cleaning and rebuilding project several times, I could read all the properties except the List of user defined class object (List<LogComponents> in below class) which is still getting read as null.
I tried all the possible solutions but nothing worked for me.
Could you please check and help me in understanding what I have missed in below code because of which the value for List<LogComponent> logComponents is still getting read as null from yml file?
Thanking you in anticipation!
Configuration Java Class
#Configuration
#EnableConfigurationProperties
#ConfigurationProperties
public class TestAPIConfiguration {
private String eventCache;
private String diskBasedCache;
private List<String> sendAllSMSto;
private List<String> sendAllEmailsto;
//This property is getting read as null even if
//value for this property is present in yml file.
private List<LogComponent> logComponents;
#NotNull
private String selfURIPrefix;
#NotNull
private String investURIPrefix;
#NotNull
private String ifaURIPrefix;
private String apiEnv;
private final Joiner joiner = Joiner.on( "," ).skipNulls();
private static final Logger LOGGER = LoggerFactory.getLogger(TestAPIConfiguration.class);
#PostConstruct
public void setSystemProperties()
{
try
{
System.setProperty(SystemConstants.EVENT_CACHE_PATH, eventCache);
System.setProperty(SystemConstants.DISK_BASED_CACHE_PATH, diskBasedCache);
System.setProperty(SystemConstants.REQUEST_LOGGING_FIELDS,
JSONUtils.getObjectMapper().writeValueAsString(logComponents));
System.setProperty(SystemConstants.ENVIRONMENT_IDENTIFIER, apiEnv);
System.setProperty(INVEST_URI_PREFIX, investURIPrefix);
System.setProperty(IFA_URI_PREFIX, ifaURIPrefix);
if(sendAllSMSto != null)
System.setProperty(SEND_ALL_SMS_TO, joiner.join(sendAllSMSto));
if(sendAllEmailsto != null)
System.setProperty(SystemConstants.SEND_ALL_EMAILS_TO, joiner.join(sendAllEmailsto));
}
catch(Exception se)
{
LOGGER.error("Error in Configuration Setup: {}", se.getLocalizedMessage());
}
}
public String getEventCache() {
return eventCache;
}
public void setEventCache(String eventCache) {
this.eventCache = eventCache;
}
public String getDiskBasedCache() {
return diskBasedCache;
}
public void setDiskBasedCache(String diskBasedCache) {
this.diskBasedCache = diskBasedCache;
}
public List getSendAllSMSto() {
return sendAllSMSto;
}
public void setSendAllSMSto(List<String> sendAllSMSto) {
this.sendAllSMSto = sendAllSMSto;
}
public List getSendAllEmailsto() {
return sendAllEmailsto;
}
public void setSendAllEmailsto(List<String> sendAllEmailsto) {
this.sendAllEmailsto = sendAllEmailsto;
}
public List getRequestLoggingFields() {
return logComponents;
}
public void setRequestLoggingFields(List<LogComponent> requestLoggingFields) {
this.logComponents = requestLoggingFields;
}
public String getSelfURIPrefix() {
return selfURIPrefix;
}
public void setSelfURIPrefix(String selfURIPrefix) {
this.selfURIPrefix = selfURIPrefix;
}
public String getInvestURIPrefix() {
return investURIPrefix;
}
public void setInvestURIPrefix(String investURIPrefix) {
this.investURIPrefix = investURIPrefix;
}
public String getIfaURIPrefix() {
return ifaURIPrefix;
}
public void setIfaURIPrefix(String ifaURIPrefix) {
this.ifaURIPrefix = ifaURIPrefix;
}
public String getApiEnv() {
return apiEnv;
}
public void setApiEnv(String apiEnv) {
this.apiEnv = apiEnv;
}
}
LogComponent Java Class
#Component
public class LogComponent {
#NotNull
private String headerName;
#NotNull
private String sessionKey;
#NotNull
private String logPrintKey;
public String getHeaderName() {
return headerName;
}
public String getSessionKey() {
return sessionKey;
}
public String getLogPrintKey() {
return logPrintKey;
}
}
application.yml File
debug: true
server:
port: 8080
apiEnv: UAT
selfURIPrefix: "https://testurl.localhost.net"
investURIPrefix: "https://testurl.mediaserver.net"
ifaURIPrefix: "https://testurl.secondaryserver.net"
sendAllSMSto:
- "0000000000"
sendAllEmailsto:
- "abc#testmail.com"
eventCache: "C:\\Users\\username\\project\\devnull\\eventcachepurchase.mdb"
diskBasedCache: "C:\\Users\\username\\project\\devnull\\cache.mdb"
logComponents:
- headerName: X-RT-REQUEST-TRACKER
sessionKey: NOT AVAILABLE
logPrintKey: REQUEST-TRACKER
- headerName: X-RT-INX-DWD
sessionKey: IFX-PDR
logPrintKey: PDR_NO
- headerName: X-RT-IFA-ARN
sessionKey: IRX-AXRN
logPrintKey: AXR-CDODEEE
Finally, I found the solution.
I had not created setter methods inside the LogComponent class because of which the values were not getting assigned to the variables.
After adding the setters for all the fields, this issue has been resolved.
Let's say if I have a test that uses builders to construct objects. The problem is that the builder() method in the builder class is static.
Generally, mocking a static method is already an indicator of bad design. However, in the case of builders, the builder() methods are always static. What's the best approach to unit testing methods using builders()? Should the builders be refactored into a separate class to facilitate mocking?
class Service {
private SqsClient sqsClient;
private String sqsQueueUrl;
public Service(String sqsQueueUrl) {
this.sqsClient = SqsClient.builder().build();
this.sqsQueueUrl = sqsQueueUrl;
}
public SqsClient getClient() {
return this.client;
}
public SqsClient setClient(SqsClient client) {
this.client = client;
}
public String getSqsQueueUrl() {
return this.sqsQueueUrl;
}
public void setSqsQueueUrl(String sqsQueueUrl) {
this.sqsQueueUrl = sqsQueueUrl;
}
public void onEvent(Activity activity) {
// How to mock builders in unit test?
DeleteMessageRequest deleteRequest = DeleteMessageRequest.builder().queueUrl(this.sqsQueueUrl).receiptHandle(activity.getReceiptHandle()).build();
DeleteMessageResponse deleteMessageResponse = this.sqsClient.deleteMessage(deleteRequest);
}
}
class ServiceTest {
#Test
public void testEvent() {
String sqsQueueUrl = "http://127.0.0.1";
String receiptHandle = "asdasd";
SqsClient sqsClient = EasyMock.mock(SqsClient.class);
Service service = EasyMock.mock(Service.class);
// EasyMock expect and replay here.
service.setClient(sqsClient);
service.setSqsQueueUrl(sqsQueueUrl);
Activity activity1 = new Activity();
activity.setReceiptHandle(receiptHandle);
service.onEvent(activity);
}
}
I have an interface:
public interface SenderService {
String send(long amount);
}
And I have an implementation of this interface:
public class SenderServiceAdapter implements SenderService {
private final ThirdPartyService thirdPartyService;
public SenderServiceAdapter(ThirdPartyService thirdPartyService) {
this.thirdPartyService = thirdPartyService;
}
#Override
public String send(long amount) {
ThirdPartyRequest thirdPartyRequest = new ThirdPartyRequest();
thirdPartyRequest.setAmount(amount);
thirdPartyRequest.setId(UUID.randomUUID().toString());
thirdPartyRequest.setDate(new Date());
ThirdPartyResponse thirdPartyResponse = thirdPartyService.send(thirdPartyRequest);
String status = thirdPartyResponse.getStatus();
if (status.equals("Error")) throw new RuntimeException("blablabla");
return thirdPartyResponse.getMessage();
}
}
Now I want to write Unit test for this service. I need to mock thirdPartyService's method send. But I don't understand how.
public class SenderServiceAdapterTest {
private ThirdPartyService thirdPartyService;
private SenderService senderService;
#Before
public void setUp() throws Exception {
thirdPartyService = Mockito.mock(ThirdPartyService.class);
senderService = new SenderServiceAdapter(thirdPartyService);
}
#Test
public void send() {
when(thirdPartyService.send(new ThirdPartyRequest())).thenReturn(new ThirdPartyResponse());
String message = senderService.send(100L);
}
}
The ThirdPartyRequest creates in SenderServiceAdapter. How can I mock it?
Try this:
doReturn(new ThirdPartyResponse()).when(thirdPartyService).send(any(ThirdPartyRequest.class));
Also by looking your code, you will need to set something in the response, so you will have to do this:
ThirdPartyResponse response = new ThirdPartyResponse(); //or mock
response.setStatus(...);
response.setMessage(...);
doReturn(response).when(thirdPartyService).send(any(ThirdPartyRequest.class));
I got pretty simple Dictionary class that makes a call to external API.
public class Dictionary {
protected ExternalService service = new ExternalService();
public String getValue(String key, String dictionaryName) {
ExternalServiceInput input = new ExternalServiceInput();
ExternalServiceOutput output = new ExternalServiceOutput();
input.setKey(key);
input.setDictionaryName(dictionaryName);
try {
output = service.invoke(input);
} catch (Exception e) {
return null;
}
return output.getValue();
}
}
It works fine, but I wanted to write Unit Tests for this, so I decided I need to mock service.invoke().
#Mock
private ExternalService service;
#InjectMocks
private Dictionary dictionary;
#InjectMocks
private ExternalServiceOutput output;
#InjectMocks
private ExternalServiceInput input;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
input.setKey("testKey");
input.setDictionaryName("testDictionary");
output.setValue("testValue");
}
#Test
public void shouldReturnValue() throws Exception {
when(service.invoke(input)).thenReturn(output);
assertEquals(output.getValue(), dictionary.getValue(input.getKey(), input.getDictionaryName()));
}
I'v tried with Input and Output as regular field or initialize it in setUp method, everything ends up with NullPointerException at Dictionary class at
return output.getValue();
Can someone point me what I did wrong?
You should override equals and hashCode in your ExternalServiceInput class or change your mock to accept any object of ExternalServiceInput
when(service.invoke(Mockito.any(ExternalServiceInput.class))).thenReturn(output);
Im currently using a Data Provider to enter numerous different users, but when the tests ends then the previous user is still logged in, how do make the bowser reset after each run? Heres my code:
public class login_from_login_page extends ConditionsWebDriverFactory {
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
#Test(dataProviderClass = Data.DataProviders.class, dataProvider = "customer")
public void LoginActionTest (String pass, String email, String user) throws Exception{
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.LoginAction(pass, email, user);
//TestRail.addResultForTestCase("16870",TEST_CASE_PASSED_STATUS," ");
//TestRail.addResultForTestCase("16874",TEST_CASE_PASSED_STATUS," ");
//TestRail.addResultForTestCase("17199",TEST_CASE_PASSED_STATUS," ");
}
}
I have a Webdriverfactory class that is extended from my test class here but its doesn't seem to be creating a new instance, im always still logged in when it restarts using the new DataProvider information.
#Listeners({ScreenShotOnFailListener.class})
public class ConditionsWebDriverFactory {
#BeforeClass
public void beforeTest() {
Drivers.startBrowser(true);
Drivers.getDriver().manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
#AfterClass (alwaysRun = true)
public void afterTest() {
Drivers.finishBrowser();
}
}
Start your test with initialization before test execution:
#BeforeMethod
void setupTest() {
WebDriver driver = new ChromDriver();
// method code here
}
Alternatively initialize your page object with new driver instance:
Pages.Login login = new Pages.Login(new ChromDriver());
Another alternative:
#Test
void seleniumTest() {
// Test code here
login.getDriver().manage().deleteAllCookies();
login.getDriver().navigate.refresh();
}
You can add after method, if you use testng:
#AfterMethod
void deleteCoockies() {
Drivers.getDriver().manage().deleteAllCookies();
Drivers.getDriver().get ("homePageUrl");
}