Is there an equivalent to #Before or beforeEach in Scalatest - scalatest

Test frameworks like jasmine and junit provide ways to configure the test environment before each test is run. Is something similar available in scalatest and playspec?

In scalatest you can use traits BeforeAndAfterAll and BeforeAndAfterEach to add such methods, then you need to override them fe:
class BaseTest extends FlatSpec with BeforeAndAfterAll with BeforeAndAfterEach{
override def beforeAll(): Unit = {
super.beforeAll()
//your logic here
}
//..
}

Related

How to inject a Drone instance without managing its lifecycle?

I have a Graphene Page Object.
#Location("/page")
public class MyPage {
#Drone
private WebDriver driver;
// page methods using the driver
}
And a Test Class that uses the page object.
#RunWith(Arquillian.class)
public class MyTest {
#Test
public void test(#InitialPage MyPage page) {
// use page & assert stuff
}
#Test
public void anotherTest(#InitialPage MyPage page) {
// use page & assert stuff even harder
}
}
Now, I've decided that MyTest should use method scoped Drone instances. So I add...
public class MyTest {
#Drone
#MethodLifecycle
private WebDriver driver;
Now when I run the test I get two browsers and all tests end with errors. Apparently this lifecycle management is treated as a qualifier too.
Yes, adding #MethodLifecycle in MyPage too helps. But this is not a solution - a page shouldn't care about this and should work in any WebDriver regardless of its scope. Only tests have the knowledge to manage the drone lifecycles. A page should just use whatever context it was invoked in. How can I achieve that?
This may be the answer:
public class MyPage {
#ArquillianResource
private WebDriver driver;
But I'm afraid that this skips some Drone-specific enriching. Also not sure if it will correctly resolve when there are multiple Drone instances.

Testing of static methods with PHPUnit

I want to test a method. This method used the static method verifyPassword() in an abstract class.
class Authentication {
...
public function onUserAuthenticate($credentials) {
….
$checkedIn = UHelper::verifyPassword($credentials);
…
}
Now I created a mock object in my test method, because I want not test the verifyPassword() with this test.
class AuthenticationTest {
..
public function testonUserAuthenticate {
...
$uhelper = $this->getMockForAbstractClass(\UHelper::class);
$uhelper->expects($this->any())
->method('verifyPassword')
->with($mypassword)
->will($this->returnValue(true));
$this->class = new \Authentication();
$this->class->onUserAuthenticate($credentials);
..
}
How can I accomplish, that my mock object is used in the test method when I run $this->class->onUserAuthenticate($credentials) ?
verifyPassword is a call to a static methode in the abstract class UHelper, so I do not have a setUHelper method anywhere.
hat I'm trying to do is make variable class Authentication in ther call of the method onUserAuthenticate use the stub $uhelper. That is not answered in the related question.

mockStatic: mock java.lang with PowerMock

I am trying to mock MBeanServer with Mockito, but my attempts fails.
#Test
public void testGetAllCacheProperties() {
mockStatic(ManagementFactory.class);
MBeanServer server = MBeanServerFactory.newMBeanServer();
ObjectInstance inst = server.registerMBean(new MyBeanService(), ObjectName.getInstance(SERVICE_NAME));
given(ManagementFactory.getPlatformMBeanServer()).willReturn(server);
}
I suppose to inject my mock into method that normally runs on jBoss AS 7:
#GET
public Response getAllProperties() {
MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
But it fails with exception:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
JmxMBeanServer cannot be returned by getPlatformMBeanServer()
getPlatformMBeanServer() should return MBeanServer
Update
When I try
PowerMockito.doReturn(server).when(ManagementFactory.class, "getPlatformMBeanServer");
I get exception:
java.lang.LinkageError: loader constraint violation: when resolving method "java.lang.management.ManagementFactory.getPlatformMBeanServer()Ljavax/management/MBeanServer;" the class loader (instance of org/powermock/core/classloader/MockClassLoader) of the current class, my_package_for_test_class.TestClass, and the class loader (instance of <bootloader>) for the method's defining class, java/lang/management/ManagementFactory, have different Class objects for the type javax/management/MBeanServer used in the signature
There is not possible to mock static from java.lang package, since PowerMock tries to change bite code and bite code of java.lang classes
obviously protected from modifications.
There is work around suggested by Johan Haleby.
You have to create wrapper class:
public class JmxUtils {
public static MBeanServer getPlatformMbeanServer() {
return ManagementFactory.getPlatformMBeanServer();
}
}
Then test will look like this
#RunWith(PowerMockRunner.class)
#PrepareForTest(JmxUtils.class)
public class CacheControllerTest {
//.. preconditions
given(JmxUtils.getPlatformMbeanServer()).willReturn(server);

EasyMock 3.2: How to address public variables in a mocked class?

I'm trying to mock an open-source class. That class uses a number of public variables instead of get methods. I need to have the mocked class return another mocked class when that variable is accessed, but I'm not sure how. Here's an example:
SolrQueryRequest request = createNiceMock(SolrQueryRequest.class);
...
replay(request);
ResponseBuilder builder = createNiceMock(ResponseBuilder.class);
expect(builder.req).andReturn(request); // Throws exception
replay(builder);
The above example, however, throws the exception java.lang.IllegalStateException: no last call on a mock available on the builder.req line. Any idea how I can do this? Please note I don't have the option of refactoring the mocked classes.
Well, after playing around with it more I discovered it was pretty easy:
myBuilder.req = request;
Now when my class under test accesses the myBuilder.req variable, it is correctly set to my mocked SolrQueryRequest.

Android Unit Tests Requiring Context

I am writing my first Android database backend and I'm struggling to unit test the creation of my database.
Currently the problem I am encountering is obtaining a valid Context object to pass to my implementation of SQLiteOpenHelper. Is there a way to get a Context object in a class extending TestCase? The solution I have thought of is to instantiate an Activity in the setup method of my TestCase and then assigning the Context of that Activity to a field variable which my test methods can access...but it seems like there should be an easier way.
You can use InstrumentationRegistry methods to get a Context:
InstrumentationRegistry.getTargetContext() - provides the application Context of the target application.
InstrumentationRegistry.getContext() - provides the Context of this Instrumentation’s package.
For AndroidX use InstrumentationRegistry.getInstrumentation().getTargetContext() or InstrumentationRegistry.getInstrumentation().getContext().
New API for AndroidX:
ApplicationProvider.getApplicationContext()
You might try switching to AndroidTestCase. From looking at the docs, it seems like it should be able to provide you with a valid Context to pass to SQLiteOpenHelper.
Edit:
Keep in mind that you probably have to have your tests setup in an "Android Test Project" in Eclipse, since the tests will try to execute on the emulator (or real device).
Your test is not a Unit test!!!
When you need
Context
Read or Write on storage
Access Network
Or change any config to test your function
You are not writing a unit test.
You need to write your test in androidTest package
Using the AndroidTestCase:getContext() method only gives a stub Context in my experience. For my tests, I'm using an empty activity in my main app and getting the Context via that. Am also extending the test suite class with the ActivityInstrumentationTestCase2 class. Seems to work for me.
public class DatabaseTest extends ActivityInstrumentationTestCase2<EmptyActivity>
EmptyActivity activity;
Context mContext = null;
...
#Before
public void setUp() {
activity = getActivity();
mContext = activity;
}
... //tests to follow
}
What does everyone else do?
You can derive from MockContext and return for example a MockResources on getResources(), a valid ContentResolver on getContentResolver(), etc. That allows, with some pain, some unit tests.
The alternative is to run for example Robolectric which simulates a whole Android OS. Those would be for system tests: It's a lot slower to run.
You should use ApplicationTestCase or ServiceTestCase.
Extending AndroidTestCase and calling AndroidTestCase:getContext() has worked fine for me to get Context for and use it with an SQLiteDatabase.
The only niggle is that the database it creates and/or uses will be the same as the one used by the production application so you will probably want to use a different filename for both
eg.
public static final String NOTES_DB = "notestore.db";
public static final String DEBUG_NOTES_DB = "DEBUG_notestore.db";
First Create Test Class under (androidTest).
Now use following code:
public class YourDBTest extends InstrumentationTestCase {
private DBContracts.DatabaseHelper db;
private RenamingDelegatingContext context;
#Override
public void setUp() throws Exception {
super.setUp();
context = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test_");
db = new DBContracts.DatabaseHelper(context);
}
#Override
public void tearDown() throws Exception {
db.close();
super.tearDown();
}
#Test
public void test1() throws Exception {
// here is your context
context = context;
}}
Initialize context like this in your Test File
private val context = mock(Context::class.java)

Resources