Selenium- Run a method once and use the return value for all #Test methods in the class - selenium

My requirement goes like this.
Log in to the application and open the System property menu to return a value of the property.
Open Another menu in the application and based on the value returned in the above step, perform the test scenario.
The problem is, for each #Test methods in the same class I need to perform both step 1 and 2 which is a time taking and unnecessary. The property retrieved from 'step 1' will be the same throughout the execution of the tests in the class.
Is there anyway I can execute 'step 1' just once at the start of the test and use the property value returned for all the #Test methods in the class following it?
P.S- I checked on the dependsOnMethods annotation and not sure whether it is a solution I am looking for.

If you're using JUnit, it sounds like #BeforeClass is what you are looking for. Method with this annotation runs only once per class and you can store any value returned in a global variable. Or, you might consider #Before annotation (runs before each test) if that suits you better.
Other testing frameworks use similar idea.

Related

Intelijj Idea move Junit tests to new class while refactoring

I have a class A with code and class ATest with tests: testcase1, testcase2... . I added new code to A and new testcaseN to ATest. During refactoring, I observed that class A is to big and could be split into two separate classes: A and B. Some test cases should be moved from ATest to newly created BTest.
Is there any method to do this automatically in Intellij to move selected methods and change access to remaining ATest class properties and help methods?
You can place the cursor on the method name, that you wish to move. Then select Refactor -> Move instance method.... There will be a wizard on what to do next for related instances, helper methods...

ParameterizedTest in Junit5

I've been looking at examples of parameterizing tests in junit 5 (which I am new to), but have not found what I'm looking for (unless I'm misunderstanding how to use them).
Basically I want to write a single (selenium/UI based) test and make it run multiple times. The paramaters I want to base the multiple runs on are custom objects that I have in my codebase.
An example I'm trying to implement would be - my test creates an appointment on a calendar with a customer, then does some assertions as to whether the appointment shows correctly and has expected details. A second test run would do the same but WITHOUT a customer. The assertions between the two test runs might slightly differ but largely the same code is run both times.
All the examples I seem to come across use primitive types like strings, or csv files, or methodSource, but none of these seem to fit what I'm trying to do.
Any help would be appreciated.
With #MethodSource you can return Arguments instances that contain literally any kind of objects you want. There are no limitations regarding primitives, etc.
For a concrete example, check out the testWithMultiArgMethodSource() example in the #MethodSource section of the JUnit 5 User Guide.
Below is a working example to showcase some variations of using #ParameterizedTest
Example with inline parameters in the #ValueSource
#DisplayName("compare the name case insensetive")
#ValueSource(strings = {"sanjAY", "SanjAY", "SANJay", "sanJAy"})
#ParameterizedTest
void compareTest(String sampleName) {
assertThat(sampleName.toUpperCase().equals("SANJAY"));
}
Additionally we can annotate with #NullAndEmptySource which will test your code against null and empty strings
Example when parameters are complex.
#DisplayName("compare the name case insensetive")
#MethodSource("com.example.TestSamples#sampleNames")
#ParameterizedTest
void compareTest(List<String> names) {
names.stream().forEach(x-> assertThat(x.endsWith("a")));
}
Create a class TestSamples in com.example package and put below method
public static List<String> sampleNames() {
return List.of("Ganga","Yamuna","Radha","Java","Lava");
}

NSubstitute Test against classes (VB.net)

First of all I'm a beginner in unit tests. For my tests i want to use NSubstitute, so I read the tutorial on the website and also the mock comparison from Richard Banks. Both of them are testing against interfaces, not against classes. The statement is "Generally this [substituted] type will be an interface, but you can also substitute classes in cases of emergency."
Now I'm wondering about the purpose of testing against interfaces. Here is the example interface from the NSubstitute website (please note, that i have converted the C#-code in VB.net):
Public Interface ICalculator
Function Add(a As Double, b As Double) As Double
Property Mode As String
Event PoweringUp As EventHandler
End Interface
And here is the unit test from the website (under the NUnit-Framework):
<Test>
Sub ReturnValue_For_Methods()
Dim calculator = Substitute.For(Of ICalculator)()
calculator.Add(1, 2).Returns(3)
Assert.AreEqual(calculator.Add(1, 2), 3)
End Sub
Ok, that works and the unit test will perform successful. But what sense makes this? This do not test any code. The Add-Method could have any errors, which will not be detected when testing against interfaces - like this:
Public Class Calculator
Implements ICalculator
Public Function Add(a As Double, b As Double) As Double Implements ICalculator.Add
Return 1 / 0
End Function
...
End Class
The Add-Method performs a division by zero, so the unit test should fail - but because of testing against the interface ICalculator the test is successful.
Could you please help me to understand that? What sense makes it, not to test the code but the interface?
Thanks in advance
Michael
The idea behind mocking is to isolate a class we are testing from its dependencies. So we don't mock the class we are testing, in this case Calculator, we mock an ICalculator when testing a class that uses an ICalculator.
A small example is when we want to test how something interacts with a database, but we don't want to use a real database for some quick tests. (Please excuse the C#.)
[Test]
public void SaveTodoItemToDatabase() {
var substituteDb = Substitute.For<IDatabase>();
var todoScreen = new TodoViewModel(substituteDb);
todoScreen.Item = "Read StackOverflow";
todoScreen.CurrentUser = "Anna";
todoScreen.Save();
substituteDb.Received().SaveTodo("Read StackOverflow", "Anna");
}
The idea here is we've separated the TodoViewModel from the details of saving to the database. We don't want to worry about configuring a database, or getting a connection string, or having data from previous test runs interfering with future tests runs. Testing with a real database can be very valuable, but in some cases we just want to test a smaller unit of functionality. Mocking is one way of doing this.
For the real app, we'll create a TodoViewModel with a real implementation of IDatabase, and provided that implementation follows the expected contract of the interface then we can have a reasonable expectation that it will work.
Hope this helps.
Update in response to comment
The test for TodoViewModel assumes the implementation of the IDatabase works so we can focus on that class' logic. This means we'll probably want a separate set of tests for implementations of IDatabase. Say we have a SqlServerDbimplementation, then we can have some tests (probably against a real database) that check it does what it promises. In those tests we'll no longer be mocking the database interface, because that's what we're testing.
Another thing we can do is have "contract tests" which we can apply to any IDatabase implementation. For example, we could have a test that says for any implementation, saving an item then loading it up again should return the same item. We can then run those tests against all implementations, SqlDb, InMemoryDb, FileDb etc. In this way we can state our assumptions about the dependencies we're mocking, then check that the actual implementations meet our assumptions.

Object methods and stats - the best object oriented design approach question

I need to write some instance method, something like this (code in ruby):
def foo_bar(param)
foo(param)
if some_condition
do_bar(param)
else
do_baz(param)
end
end
Method foo_bar is a public api.
But I think, param variable here appears too many times. Maybe it would be better to create an private instance variable and use it in foo, do_bar and do_baz method? Like here: (#param is an instance variable in ruby, it can be initialized any time)
def foo_bar(param)
#param = param
foo
if some_condition
do_bar
else
do_baz
end
end
Which code is better? And why?
Is param replacing part of the state of the object?
If param is not changing the object state then it would be wrong to introduce non-obvious coupling between these methods as a convenience.
If param is altering the state of the object then it may still be bad practice to have a public api altering the state - much better to have a single private method responsible for checking and changing the state.
If param is directly setting the state of the object then I would change the instance variable here but only after checking that the new state is not inconsistent
The first version should be preferred for a couple of reasons. First, it makes testing much easier as each method is independent of other state. To test the do_bar method, simply create an instance of its containing class and invoke the method with various parameters. If you chose the second version of code, you'd have to make sure that the object had all the proper instance variables set before invoking the method. This tightly couples the test code with the object and results in broken test cases or, even worse, testcases that should no longer pass, but still do since they haven't been updated to match how the object now works.
The second reason to prefer the first version of code is that it is a more functional style and facilitates easier reuse. Say that another module or lambda function implements do_bar better than the current one. It won't have been coded to assume some parent class with a certain named instance variable. To be reusable, it will have expected any variables to be passed in as parameters.
The functional approach is the much better approach ... even in object oriented languages.
If you do not need param outside of the foo_bar method the first version is better. It is more obvious what information is being passed around and you are keeping it more thread friendly.
And I also agree with Mladen in the comment above: don't add something to the object state that doesn't belong there.

naming a method - using set() when *not* setting a property?

Is setX() method name appropriate for only for setting class property X?
For instance, I have a class where the output is a string of an html table. Before you can you can call getTable, you have to call setTable(), which just looks at a other properties and decides how to construct the table. It doesn't actually directly set any class property -- only causes the property to be set. When it's called, the class will construct strHtmlTable, but you can't specify it.
So, calling it setTable breaks the convention of get and set being interfaces for class properties.
Is there another naming convention for this kind of method?
Edit: in this particular class, there are at least two ( and in total 8 optional ) other methods that must be called before the class knows everything it needs to to construct the table. I chose to have the data set as separate methods rather than clutter up the __construct() with 8 optional parameters which I'll never remember the order of.
I would recommend something like generateTable() instead of setTable(). This provides a situation where the name of the method clearly denotes what it does.
I would probably still use a setTable() method to actually set the property, though. Ideally, you could open the possibility of setting a previously defined table for further flexibility.
Yes, setX() is primarily used for setting a field X, though setX() may have some additional code that needs to run in addition to a direct assignment to a field. Using it for something else may be misleading to other developers.
I would definitely recommend against having a public setTable() and would say that setTable() could be omitted or just an unused private method depending upon your requirements.
It sounds like the activity to generate the table is more of a view of other properties on the object, so you might consider moving that to a private method on the object like generateHtmlTable(). This could be done during construction (and upon updates to the object) so that any subsequent calls to getTable() will return the the appropriate HTML.