What changes do i need to make to the following please?
I'd like make sure that testInsert method to only run when testInternalAccess passes and testInternalAccess not count as a failure.
#Test
public void testInternalAccess() {
URL url = null;
try {
url = new URL("http://internalpage");
InputStream is = url.openConnection().getInputStream();
} catch (Exception e) {
fail();
}
}
#Test(groups = "database", dependsOnMethods = "testInternalAccess")
public void testInsert() {
// some code
}
In the above example:
testInternalAccess runs, fails and being reported as a failed test
testInsert runs and fails
Or, using creator's of TestNG example
#Test
public serverStartedOk() {}
#Test(dependsOnMethods = { "serverStartedOk" })
public method1() {}
How will method1 know whether server actually started ok? How will serverstartedOk communicate to the world it's state?
Based on the discussion we had above, following is the brief summary.
As you wish to run the method testinternalAcecess before you run all the tests in the class use #BeforeClass
#BeforeSuite
public void testInternalAccess() {
URL url = null;
try {
url = new URL("http://internalpage");
InputStream is = url.openConnection().getInputStream();
} catch (Exception e) {
fail();
}
}
The method runs only once and before all tests run in the suite! And you test method would be some thing as below
#Test(groups = "database")
public void testInsert() {
// some code
}
Bingo and this would work!
Related
I have this complicated method. I want to mock just the result. All what is inside should basically be ignored. I am using Mockito .
class JiraManager
{
public static List<Issue> searchMitarbeiterIssue(String mitarbeiterName) throws JqlParseException, SearchException {
ApplicationUser user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
JqlQueryParser jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser.class);
SearchService searchService = ComponentAccessor.getComponent(SearchService.class);
String jqlSearchString = "project = BLUB AND issuetype = BLOB AND text ~ \"" + myName+ "\""+" AND status = aktive";
final Query query = jqlQueryParser.parseQuery(jqlSearchString);
List<Issue> issues = null;
Query queryToExecute = JqlQueryBuilder.newBuilder(query).buildQuery();
// get results for the jql query
SearchResults searchResult = searchService.search(user, queryToExecute, PagerFilter.getUnlimitedFilter());
try {
Method newGetMethod = null;
try {
newGetMethod = SearchResults.class.getMethod("getIssues");
} catch (NoSuchMethodException e) {
try {
LOGGER.warn("SearchResults.getIssues does not exist - trying to use getResults!");
newGetMethod = SearchResults.class.getMethod("getResults");
} catch (NoSuchMethodError e2) {
LOGGER.error("SearchResults.getResults does not exist!");
}
}
if (newGetMethod != null) {
issues = (List<Issue>) newGetMethod.invoke(searchResult);
} else {
LOGGER.error("ERROR NO METHOD TO GET ISSUES !");
throw new RuntimeException("ICT: SearchResults Service from JIRA NOT AVAILABLE (getIssue / getResults)");
}
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.error("Jql Helper can not get search result (ICT)", e);
} catch (Exception e) {
LOGGER.error("Jql Helper can not get search result - other exception (ICT)", e);
}
return issues;
}
}
I do not want Mockito to run all the Code inside the method. It should just return the List . That's all . So I tried this:
try (MockedStatic<JiraManager> utilities = Mockito.mockStatic(JiraManager.class)) {
utilities.when(() -> JiraManager.searchMitarbeiterIssue(any()))
.thenReturn(Collections.singletonList(mitarbeiterIssueResult));
assertTrue(JiraManager.searchMitarbeiterIssue("").size() == 1);
}
But it is not working. It always returns null. Why ?? Is the code inside the method executed ? What is Mockito exactly doing ?
Below works for me.
Create MockedStatic class field
private MockedStatic<MyUtilClassWithStaticMethods> myUtil;
Initialise MockedStatic before each test case
#BeforeEach
void initialiseWorker() {
myUtil = mockStatic(MyUtilClassWithStaticMethods.class);
}
Close MockedStatic after each test case
#AfterEach
public void close() {
myUtil.close();
}
Mock static method behaviour in test case
#Test
void test() {
when(MyUtilClassWithStaticMethods.staticMethod(any())).thenReturn(null);
}
You can return list instead of null here.
I want to store errors in excel file while performing Selenium test case over HTML fields with Junit.
My code is:
public class ExceptionHandler {
public ErrorCollector errors = new ErrorCollector();
public ErrorCollector getErrors() {
return errors;
}
public void setErrors(ErrorCollector errors) {
this.errors = errors;
}
public void execute(ExceptionHandlerTemplate template) {
System.out.println("Inside execute");
try {
System.out.println("Inside try");
template.execute();
} catch (Exception exc) {
System.out.println("Inside catch: " + exc);
errors.addError(exc);
}
}
}
This code is working fine.
But how to retrieve all the errors in variable or datatype. I am using below code:
ErrorCollector errCollector = executor.getErrors();
This question already has answers here:
Mocking Files in Java - Mock Contents - Mockito
(3 answers)
Closed 6 years ago.
I have the following code:
public class FolderServiceImpl implements FolderService {
private static final Logger L = LoggerFactory.getLogger(FolderServiceImpl.class);
public int getStatus(String folderPath) {
int status = 0;
File folderStatusFile = new File(folderPath, ".folderstatus");
if (folderStatusFile.exists()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(folderStatusFile));
String line = br.readLine();
status = Integer.parseInt(line);
} catch (Exception e) {
L.error("can't read file " + folderStatusFile.getAbsolutePath(), e);
status = 4;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
L.warn("could not close reader ", e);
}
}
}
} else {
status = 3;
}
return status;
}
}
I want to test this method without creating actual files for every case. I should be using Java 1.7, JUnit 4, Mockito and/or PowerMockito.
Any ideas on how to do that?
I am talking about mocking either the data source or simply changeing the input for the method.
My test looks something like this:
`#Rule
public TemporaryFolder folder = new TemporaryFolder();
private FolderServiceImpl serviceToTest = new FolderServiceImpl();
private String folderPath;
#Before
public void setUp() {
folderPath = folder.getRoot().getAbsolutePath();
try {
folder.newFile(".folderstatus");
} catch (IOException e) {
e.printStackTrace();
}
}
#Test
public void shouldReturnFolderStatus3WhenFolderStatusIsNotFound() {
// given
deleteFolderStatusFile();
// actual
int status = serviceToTest.getFolderStatus(folderPath);
// expected
assertEquals(3, status);
}
#Test
public void shouldReturnFolderStatus4WhenTheStatusIsUnreadable() {
// given
writeStatusToTestFile("Test");
// actual
int status = serviceToTest.getFolderStatus(folderPath);
// expected
assertEquals(4, status);
}
#Test
public void shouldReturnFolderStatusInTheFile() {
// given
writeStatusToTestFile("1");
// actual
int status = serviceToTest.getFolderStatus(folderPath);
// expected
assertEquals(1, status);
}
private void writeStatusToTestFile(String status) {
Path file = Paths.get(folder.getRoot().getAbsolutePath(), ".folderstatus");
try {
Files.write(file, status.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private void deleteFolderStatusFile() {
Path file = Paths.get(folder.getRoot().getAbsolutePath(), ".folderstatus");
try {
Files.delete(file);
} catch (IOException e) {
e.printStackTrace();
}
}`
Although the answer of #BenHeid may work I'd suggest to change to different approach.
IMHO when ever I use PowerMock(-ito) it is a surrender to bad design.
Also the PowerMock solution will confuse test coverage tools since it changes the Applications byte code after it has been instrumented for coverage measurement.
So the approach I'd prefer is to stick to Clean Code and OOP rules.
One of them is separation of concerns.
In your case the method creates some infrastructure classes (dependencies) to work with, namely FileReader and BufferedReader.
But the instantiation of (direct) dependencies is not a responsibility of a class containing business logic.
Therefore I'd suggest to refactor that code out into a separate class:
class ReaderFactory {
public BufferedReader createFor(File file) throws FileNotFoundException {
return new BufferedReader(new FileReader(file));
}
}
Your Class would change to this:
class FolderServiceImpl {
private static final Logger L = LoggerFactory.getLogger(FolderServiceImpl.class);
private final ReaderFactory readerFactory;
FolderServiceImpl(ReaderFactory readerFactory) {
this.readerFactory = readerFactory;
}
public int getStatus(String folderPath) {
int status = 0;
File folderStatusFile = new File(folderPath, ".folderstatus");
// try "with resource" takes care of closing the reader
try (BufferedReader br = readerFactory.createFor(folderStatusFile);) {
String line = br.readLine();
status = Integer.parseInt(line);
} catch (IOException e) {
status = 3;
} catch (Exception e) {
L.error("can't read file " + folderStatusFile.getAbsolutePath(), e);
status = 4;
}
return status;
}
}
And your Test would be this:
public class FolderServiceImplTest {
private static final String ANY_FILE_NAME = "";
#Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
#Rule
public ExpectedException thrown = ExpectedException.none();
#Mock
private ReaderFactory readerFactory;
#InjectMocks
FolderServiceImpl sut;
#Test
public void getStatus_FileNotExisting_returnStatus3() throws Exception {
// arrange
Mockito.doThrow(new FileNotFoundException("UnitTest")).when(readerFactory).createFor(Mockito.any(File.class));
// act
int status = sut.getStatus(ANY_FILE_NAME);
// assert
Assert.assertThat("status",status,CoreMatchers.equalTo(3));
}
#Test
public void getStatus_ValidFile_returnFileContentAsInt() throws Exception {
// arrange
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.doReturn(bufferedReader).when(readerFactory).createFor(Mockito.any(File.class));
Mockito.doReturn("4711").when(bufferedReader).readLine();
// act
int status = sut.getStatus(ANY_FILE_NAME);
// assert
Assert.assertThat("status",status,CoreMatchers.equalTo(4711));
}
}
You have to use something like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(tests.class)
public class test {
#Test
public void test() throws Exception {
File fileMock = Mockito.mock(File.class);
PowerMockito.whenNew(File.class).withArguments(Mockito.anyString(), Mockito.anyString()).thenReturn(fileMock);
FolderServiceImpl sut = new FolderServiceImpl sut ();
Mockito.when(fileMock.exists()).thenReturn(true);
sut.getStatus("");
// Your verifications..
}
}
Powermock will mock the File object which is created in the method getStatus of your class. With Mockito.when you can say what is the return value of folderStatusFile.exists() in your code.
EDIT
I have included the following two jars with maven, but you don't need to use maven: https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4/1.4.6 and https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito/1.4.9 and https://mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19
I am creating a basic POST JSON api endoint. I would like to unit test it, and want to make sure I am doing it appropriately in the Play framework. So far I am using Guice for dependency injection and JUnit for my unit testing library.
Here is my controller code:
public class NotificationController extends Controller {
private RabbitQueueService _rabbitQueueService;
#Inject
public NotificationController(RabbitQueueService service) {
_rabbitQueueService = service;
}
#BodyParser.Of(BodyParser.Json.class)
public Result post() {
ObjectMapper mapper = new ObjectMapper();
Notification notification;
try {
JsonNode notificationJsonNode = Controller.request().body().asJson();
notification = mapper.readValue(notificationJsonNode.toString(),
Notification.class);
_rabbitQueueService.push(notification);
return Results.created(notificationJsonNode, "UTF-8");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Results.badRequest();
}
}
My RabbitQueueService code:
public class RabbitQueueService {
private Channel _channel;
private Connection _connection;
public RabbitQueueService() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(Config.RABBITMQ_HOST);
try {
_connection = factory.newConnection();
_channel = _connection.createChannel();
_channel.queueDeclare(Config.RABBITMQ_QUEUE, false, false, false, null);
_channel.exchangeDeclare(Config.RABBITMQ_EXCHANGE, "fanout");
_channel.queueBind(Config.RABBITMQ_QUEUE, Config.RABBITMQ_EXCHANGE, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public void push(Notification notification) {
try {
_channel.basicPublish(Config.RABBITMQ_EXCHANGE, "", null, notification.getBytes());
_channel.close();
_connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pop() {
}
}
My MockQueueService code:
public class MockQueueService extends RabbitQueueService {
#Override
public void push(Notification notification) {
/* Do nothing because you know... thats what I do */
}
#Override
public void pop() {
/* Do nothing because you know... thats what I do */
}
}
and finally my current unit test code:
public class ApplicationTest {
#Test
public void addMessageToQueue() {
running(fakeApplication(), new Runnable() {
public void run() {
FakeRequest request = new FakeRequest("/POST", "/api/v1/notifications");
Notification notification = new Notification(UUID.randomUUID(),
new NotificationType(UUID.randomUUID(),
"Critical"),
"Test notification message");
try {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(notification);
JsonNode node;
node = mapper.readTree(json);
request.withJsonBody(node);
} catch (IOException e) {
e.printStackTrace();
}
route(request);
}
});
}
}
This all works fine when making a curl request to test my endpoint through play run. My main question is: how do I use the MockQueueService in my unit test? I don't see anyway to do it with fakeApplication() helper. I could instantiate it directly like
NotificationController nc = new NotificationController(new MockQueueService());
nc.post();
but the problem is I need to override the body of the play request with an appropriate request body and I think I need a FakeRequest for that.
Any help, samples, or advice would be helpful.
UPDATE
I have posted a gist example with the necessary example files. The things specifically that I did to get it working:
Setup a new GlobalUnitTest file that I passed into the fakeApplication helper
Changed NotificationController to be a singleton. This allowed me to pull in the NotificationController instance so I could check the QueueService count as part of the assertion.
FakeApplication takes a bunch of arguments that you could use to inject your new service. You could use a combination of any of these:
additionalPlugins
additionalConfiguration
withGlobal
They each let you specify some additional configuration you could use only during testing. Another thing you could do is have a separate Global object just for testing, that is used to create your controllers. The Global object is used to return your controller instance when you use # in your route definition. Then, you can create a separate application.test.conf that refers to GlobalTest that is loaded when you run play test.
When I run a test with Robotium, I use an assertion to verify that there is specific text on the page, but it fails. However, when I run the test without the assertion, the test passes. Why would this be?
Here is my code:
import com.jayway.android.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.Smoke;
#SuppressWarnings("unchecked")
public class ODPRobotiumTest extends ActivityInstrumentationTestCase2 {
private static final String TARGET_PACKAGE_ID = "com.gravitymobile.app.hornbill";
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.vzw.odp.LaunchActivity";
private static Class<?>launcherActivityClass;
static{
try{
launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e){
throw new RuntimeException(e);
}
}
#SuppressWarnings({ "unchecked", "deprecation" })
public ODPRobotiumTest() throws ClassNotFoundException{
super(TARGET_PACKAGE_ID, launcherActivityClass);
}
private Solo solo;
#Override
protected void setUp() throws Exception{
solo = new Solo(getInstrumentation(), getActivity());
}
#Smoke
public void testLine1(){
try {
assertTrue(solo.searchText("Easy to Find")) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Smoke
public void testLine2(){
try{
solo.searchText("Hassle-Free");
}catch(Exception e){
e.printStackTrace();
}
}
#Smoke
public void testLine3(){
solo.searchText("Trust");
}
public void testLine4(){
solo.searchText("Verizon Curated Wallpaper");
}
public void testLine5(){
solo.searchText("Taco's");
}
#Override
public void tearDown() throws Exception{
try{
solo.finalize();
}catch(Throwable e){
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
}
The test in testLine1 is the test that fails. But like I said before, when I don't use the assertTrue, and just solo.searchTest("Easy to find"), the test will pass. I don't understand.
Thanks for any help!
If you don't assert anything then your test will pass cause nothing can fail.
Obviously the text you are searching is either missing from the screen, your configuration of the test runner is wrong or you are not even using the correct mechanisms for searching.
I just found out the content that I am trying to verify is HTML. So since Robotium doesn't work with HTML, or any other web component, it won't verify the text I'm looking for.
Thank you to all who offered help!