How to write assertTimeoutPreemptively (JUnit 5) in JUnit 4? - java

Till now I was working on JUnit 5 and now I have to work on an old system with JUnit 4 and I cannot update JUnit 5 there. I have a test in JUnit 5 that I have to write in JUnit 4 but I am not sure how it will work or how to write? Below is the JUnit 5 version of the test.
#AfterEach
void afterEach() throws Exception {
// Bleed off any events that were generated...
assertTimeoutPreemptively(ofMillis(MESSAGE_CLEARING_TIMEOUT_MS), () -> {
boolean tryAgain = true;
while (tryAgain) {
try {
final IMessageFacade message = messageConsumer.receiveMessage(MESSAGE_TIMEOUT_MS);
message.acknowledge();
} catch (MessagingException e) {
tryAgain = false;
}
}
});
broker.stop();
}
In the test, I am using assertTimeoutPreemptively() and am not sure how to convert it to JUnit 4. I tried putting a timeout which is a global timeout in JUnit 4 but that didn't work. Any guidance in terms of writing above #AfterEach condition with JUnit 4?

Shouldn't assertions run only once? Finding asserts in test teardown is somehow surprising. Consider to make your assertions part of your tests.
In JUnit 5 this looks like:
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
public class TimeoutJUnit5Test {
#Test #Timeout(value = 10, unit = MILLISECONDS)
void junitFiveTimeout() {
// ...
}
}
and in JUnit 4:
import org.junit.Test;
public class TimeoutJUnit4Test {
#Test(timeout = 10)
public void junitFourTimeout() {
// ...
}
}
What's stopping you from using both versions of JUnit? (pom.xml):
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.5.2</version>
<scope>test</scope>
</dependency>
Last option would be to simply copy / adapt the behaviour from the new JUnit 5 assertTimeoutPreemptively() to you own project.

Related

Cucumber 6 + JUnit 5 + Spring Parallel Scenarios Execution

I've been reading a lot of documentations, posts, articles and it's said that out-of-box solution to run scenarios in a single feature file in parallel is impossible.
We can use maven-surefire-plugin to run in parallel different feature files, but not scenarios.
For example there is a feature file with scenarios:
Feature: Parallel Scenarios
Scenario: First
...
Scenario: Second
...
Scenario: Third
...
And I'd like to run all there scenarios concurrently in separated threads.
How can I achieve this?
I am using testNG with courgette-jvm to run parallel tests at scenario level
. Here is runner file
import courgette.api.CourgetteOptions;
import courgette.api.CourgetteRunLevel;
import courgette.api.CucumberOptions;
import courgette.api.testng.TestNGCourgette;
import org.testng.annotations.Test;
#Test
#CourgetteOptions(
threads = 10,
runLevel = CourgetteRunLevel.SCENARIO,
rerunFailedScenarios = true,
rerunAttempts = 1,
showTestOutput = true,
reportTitle = "Courgette-JVM Example",
reportTargetDir = "build",
environmentInfo = "browser=chrome; git_branch=master",
cucumberOptions = #CucumberOptions(
features = "src/test/resources/com/test/",
glue = "com.test.stepdefs",
publish = true,
plugin = {
"pretty",
"json:target/cucumber-report/cucumber.json",
"html:target/cucumber-report/cucumber.html"}
))
class AcceptanceIT extends TestNGCourgette {
}
and then use regular webdriver config, I use RemoteWebDriver
protected RemoteWebDriver createDriver() throws MalformedURLException {
//wherever grid hub is pointing. it should work without grid too
String hubURL = "http://localhost:xxxx/wd/hub";
ChromeOptions options = new ChromeOptions();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
return (RemoteWebDriver) (driver = new RemoteWebDriver(new URL(hubURL), capabilities));
}
public RemoteWebDriver getDriver() throws MalformedURLException {
if (driver == null) {
this.createDriver();
}
return (RemoteWebDriver) driver;
}
you may have to utilize these dependencies
<dependency>
<groupId>io.github.prashant-ramcharan</groupId>
<artifactId>courgette-jvm</artifactId>
<version>5.11.0</version>
</dependency>
<dependency>
<!-- httpclient dpendendecy is to resolve courgette-jvm error - NoClassDefFoundError: org/apache/http/conn/ssl/TrustAllStrategy -->
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>6.9.1</version>
</dependency>

How can i make DateUtil throw an exception?

#Override
public void contextDestroyed(ServletContextEvent sce) {
try{
DateUtil.clean();
}catch(Exception e){
LOGGER.error("MyServletContextListener contextDestroyed error: ", e);
}
I am doing unit testing on the above piece of code, and am trying to get 100% line coverage by hitting the Exception clause, however, i cant seem to make it work with my implementation. Would appreciate any help yall. Please look below for my implementation.
#Test (expected= Exception.class)
public void test_contextDestroyed_Exception() {
DateUtil wrapper = Mockito.spy(new DateUtil());
Exception e = mock(Exception.class);
when(wrapper).thenThrow(e);
Mockito.doThrow(e)
.when(myServletContextListener)
.contextDestroyed(sce);
myServletContextListener.contextDestroyed(sce);
}
Since DateUtil.clean() is a static method, you can't mock it with Mockito.
You need to use PowerMockito instead:
<properties>
<powermock.version>1.6.6</powermock.version>
</properties>
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
Check official PowerMock documentation for version compatibility with JUnit and Mockito.
Once you did that, you should add the following to your test class:
#RunWith(PowerMockRunner.class) //<-- this says to JUnit to use power mock runner
#PrepareForTest(DateUtil.class) //<-- this prepares the static class for mock
public class YourTestClass {
#Test(expected = Exception.class)
public void test_contextDestroyed_Exception() {
PowerMockito.mockStatic(DateUtil.class);
when(DateUtil.clean()).thenThrow(new Exception("whatever you want"));
//prepare your test
//run your test:
myServletContextListener.contextDestroyed(sce);
}
}
you can use mockito-inline artifact from Mockito to test static methods and follow the below approach,
try (MockedStatic<DateUtil> utilities = Mockito.mockStatic(DateUtil.class)) {
utilities.when(DateUtil::clean).thenThrow(Exception.class);
// assert exception here
}
for more info,
https://frontbackend.com/java/how-to-mock-static-methods-with-mockito

NPE Testing Kafka Producer Using Embedded Kafka

I've written a basic spring boot service that consumes some data via rest API and publishes it to rabbitmq and kafka.
To test the service class handling kafka producing, I followed this guide: https://www.baeldung.com/spring-boot-kafka-testing
In isolation, the test (KafkaMessagingServiceImplTest) works perfectly both in intellij idea and via mvn on the command line. Running all project tests in idea works fine. However, when I run all project tests via maven on the command line, this test fails with an NPE when trying to make the assertion on the payload String.
I've narrowed down the location of the root problem to another test class (AppPropertiesTest) which is solely testing my AppProperties component (which is a component I use to pull config from application.properties in a tidy way). When, and only when, the tests within that test class are run alongside the failing test using 'mvn clean install' in project root, does the NPE show up. Commenting out the tests in this class or annotating it with #DirtiesContext fixes the problem. Apparently something loaded into the spring context by this test class causes an issue with the timing/order of events/countdownlatch in the other test. Of course, I don't want to use #DirtiesContext as it can lead to a much slower build as the project increases in complexity. It also does not explain the problem.. and I can't handle that :)
AppPropertiesTest uses constructor injection to inject the AppProperties component. It also extends a abstract class 'GenericServiceTest' which is annotated by:
#SpringBootTest
#TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
and contains nothing else. As you probably know, the SpringBootTest annotation builds a test spring context and wires in boilerplate to allow effective testing of a spring app's dependency injection etc. and the TestConstructor annotation allows constructor injection in some of my tests. FWIW, I have tried removing the TestConstructor annotation and using plain old Autowiring in the AppProperties class to see if it makes a difference but it does not.
The failing test class also extends GenericServiceTest, as it requires the spring context to inject some of the dependencies such as the consumer and the messaging service being tested and AppProperties instance within etc.
So I know where the problem lies but I don't know what the problem is. Even when the test fails with the NPE, I can see in the logs that the consumer has successfully consumed the message before the failure, as per the Baeldung guide :
TestKafkaConsumer : received payload='ConsumerRecord(topic = test-kafka-topic, partition = 0, leaderEpoch = 0, offset = 0, CreateTime = 1618997289238, serialized key size = -1, serialized value size = 43, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = This is a test message to be sent to Kafka.)'
However, the payLoad is null when we get back to the assertion. I've tried all kinds of things like Thread.sleep() in the failing test to give it more time and I've increased the await() timeout but no joy.
I find it bizarre that the tests are fine in IDEA and in isolation. Now it's starting to drive me a little crazy and I can't debug it because the problem doesn't occur in my IDE.
If anyone has any ideas, it would be greatly appreciated!
Thanks.
EDIT: Someone very reasonably suggested that I add some code so here goes :)
The Failing Test (fails at assertTrue(payload.contains(testMessage)) because payLoad is null). The autowired kafkaMessagingService simply has the dependencies of AppProperties and KakfaTemplate injected and calls kafkaTemplate.send():
#EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" })
class KafkaMessagingServiceImplTest extends GenericServiceTest {
#Autowired
#Qualifier("kafkaMessagingServiceImpl")
private IMessagingService messagingService;
#Autowired
private TestKafkaConsumer kafkaConsumer;
#Value("${app.topicName}")
private String testTopic;
#Test
public void testSendAndConsumeKafkaMessage() throws InterruptedException {
String testMessage = "This is a test message to be sent to Kafka.";
messagingService.sendMessage(testMessage);
kafkaConsumer.getLatch().await(2000, TimeUnit.MILLISECONDS);
String payload = kafkaConsumer.getPayload();
assertTrue(payload.contains(testMessage));
}
The TestConsumer (used to consume in the test above)
#Component
public class TestKafkaConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(TestKafkaConsumer.class);
private CountDownLatch latch = new CountDownLatch(1);
private String payload = null;
#KafkaListener(topics = "${app.topicName}")
public void receive(ConsumerRecord<?, ?> consumerRecord) {
LOGGER.info("received payload='{}'", consumerRecord.toString());
setPayload(consumerRecord.toString());
latch.countDown();
}
public CountDownLatch getLatch() {
return latch;
}
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
Project dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.5.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.kafka/spring-kafka-test -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<version>2.5.6.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
AppPropertiesTest class (the context of which seems to cause the problem)
class AppPropertiesTest extends GenericServiceTest {
private final AppProperties appProperties;
public AppPropertiesTest(AppProperties appProperties) {
this.appProperties = appProperties;
}
#Test
public void testAppPropertiesGetQueueName() {
String expected = "test-queue";
String result = appProperties.getRabbitMQQueueName();
assertEquals(expected, result);
}
#Test
public void testAppPropertiesGetDurableQueue() {
boolean isDurableQueue = appProperties.isDurableQueue();
assertTrue(isDurableQueue);
}
}
The AppProperties class that the AppPropertiesTest class is testing:
#Component
#ConfigurationProperties("app")
public class AppProperties {
// a whole bunch of properties by name that are prefixed by app. in the application.properties file. Nothing else
}
The Generic service test class which both tests extend.
#SpringBootTest
#TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
public abstract class GenericServiceTest {
}
The failure (you can see on the line above the payload has been received and printed out).
2021-04-21 14:15:07.113 INFO 493384 --- [ntainer#0-0-C-1] service.TestKafkaConsumer : received payload='ConsumerRecord(topic = test-kafka-topic, partition = 0, leaderEpoch = 0, offset = 0, CreateTime = 1619010907076, serialized key size = -1, serialized value size = 43, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = This is a test message to be sent to Kafka.)'
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.791 s <<< FAILURE! - in
service.KafkaMessagingServiceImplTest
[ERROR] testSendAndConsumeKafkaMessage Time elapsed: 2.044 s <<< ERROR!
java.lang.NullPointerException
at service.KafkaMessagingServiceImplTest.testSendAndConsumeKafkaMessage(KafkaMessagingServiceImplTest.java:42)
The problem is that TestListener is a #Component so it is being added twice - the record is going to the other instance.
I added more debugging to verify the getter is called on a different instance.
#Component
public class TestKafkaConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(TestKafkaConsumer.class);
private final CountDownLatch latch = new CountDownLatch(1);
private String payload = null;
#KafkaListener(id = "myListener", topics = "${app.kafkaTopicName}")
public void receive(ConsumerRecord<?, ?> consumerRecord) {
LOGGER.info("received payload='{}'", consumerRecord.toString());
setPayload(consumerRecord.toString());
if (payload != null) {
LOGGER.info(this + ": payload is not null still");
}
latch.countDown();
if (payload != null) {
LOGGER.info(this + ": payload is not null after latch countdown");
}
}
public CountDownLatch getLatch() {
return latch;
}
public String getPayload() {
LOGGER.info(this + ": getting Payload");
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
}
If you don't want to use #DirtiesContext, you can at least stop the listener containers after the tests complete:
#SpringBootTest
#TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
public abstract class GenericDataServiceTest {
#AfterAll
static void stopContainers(#Autowired KafkaListenerEndpointRegistry registry) {
registry.stop();
}
}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Can't initialize mongo db using ape-nosql-mongo #UsingDataSet

I want to run some integration test using Arquillian, Arquillian cube and Mongo. The desired scenario is:
Start the application in a managed container. Here I want to use Shrinkwrap to add just the service I want to test (for example dao service)
Start the database inside a docker container. Populate the db with some initial data
Run the test against the database
My test looks like this:
#Inject
MongoProducer producer;
#Test
#UsingDataSet(locations = "initialData.json")
public void shouldGetAllFromMongo() {
FindIterable<Document> documents = producer.getMongoClient().getDatabase("bearsdb").getCollection("bears").find();
documents.forEach((Block<? super Document>) e-> System.out.println(e));
}
The initialData.json is under src/test/resources and format of the seeding data is as bellow:
{
"bears": [
{
"firstName": "grizz",
"lastName": "the bear",
"age": 3
},
{
"firstName": "panpan",
"lastName": "the bear",
"age": 3
},
{
"firstName": "icebear",
"lastName": "the bear",
"age": 4
}
]}
My docker-compose file looks like this:
version: '3'
services:
mongo-test-db:
image: mongo:latest
environment:
- MONGO-INITDB-DATABASE=bearsdb
- MONGO-INITDB_ROOT_USERNAME=panda
- MONGO-INITDB_ROOT_PASSWORD=pass
ports:
- 27117:27017
I don't really know if the environments help but I saw this in an example.
My pom.xml contains:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-bom</artifactId>
<version>${version.shrinkwrap.resolvers}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.15.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.arquillian</groupId>
<artifactId>arquillian-universe</artifactId>
<version>${version.arquillian_universe}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
and as dependencies
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.arquillian.cube</groupId>
<artifactId>arquillian-cube-docker</artifactId>
<version>${org.arquillian.cube.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.arquillian.universe</groupId>
<artifactId>arquillian-ape-sql-container-dbunit</artifactId>
<scope>test</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.arquillian.universe</groupId>
<artifactId>arquillian-ape-nosql-mongodb</artifactId>
<scope>test</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.3</version>
</dependency>
Please note that I don't use the arquillian-junit-standalone dependency.
Additional note is that I'm using ShwripWrack to package and I deploy the war into an managed Wildfly 8.2.0.Final server. Additionl in the same test class I've tested also against an Postgres running inside docker and for this the #UsingDataSet works ok. Bellow is the working sql test and the createDeploy method:
#Deployment
public static WebArchive createDeployment() {
JavaArchive[] javaArchives = Maven.resolver().resolve(
"org.assertj:assertj-core:3.15.0",
"org.arquillian.cube:arquillian-cube-docker:1.18.2",
"org.mongodb:mongo-java-driver:3.4.3")
.withTransitivity().as(JavaArchive.class);
WebArchive war = ShrinkWrap.create(WebArchive.class, "app.war")
.addClasses(PersonDao.class, Person.class)
.addClasses(MongoProducer.class, PropertyProducer.class, Property.class)
.addAsLibraries(javaArchives)
.addAsResource("test-persistence.xml", ArchivePaths.create("META-INF/persistence.xml"))
.addAsResource("META-INF/application.properties", ArchivePaths.create("META-INF/application.properties"))
.addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
System.out.println(war.toString(true));
return war;
}
#Test
#org.arquillian.ape.rdbms.UsingDataSet("datasets/persons.xml")
public void shouldFindAll() {
List<Person> messages = personDao.findAll();
assertThat(messages.size()).isEqualTo(1);
}
The issue with the above test is that the database doesn't get initialize and nothing is printed out.
I managed to resolve my problem. The issue is that I forgot to add an Junit rule where the configuration to the Mongo database was set.
#Rule
public MongoDbRule mongoDbRule = new MongoDbRule(MongoDbConfigurationBuilder.mongoDb()
.host("localhost")
.port(27117)
.databaseName("pandadb")
.build());
The full test class looks like:
#RunWith(Arquillian.class)
public class PersonDaoDockerIT {
#Rule
public MongoDbRule mongoDbRule = new MongoDbRule(MongoDbConfigurationBuilder.mongoDb()
.host("localhost")
.port(27117)
.databaseName("pandadb")
.build());
#Deployment
public static WebArchive createDeployment() {
JavaArchive[] javaArchives = Maven.resolver().resolve(
"org.assertj:assertj-core:3.15.0",
"org.arquillian.cube:arquillian-cube-docker:1.18.2",
"org.mongodb:mongo-java-driver:3.4.3")
.withTransitivity().as(JavaArchive.class);
WebArchive war = ShrinkWrap.create(WebArchive.class, "app.war")
.addClasses(PersonDao.class, Person.class)
.addClasses(MongoProducer.class, PropertyProducer.class, Property.class)
.addPackages(true, "com.lordofthejars.nosqlunit")
.addAsLibraries(javaArchives)
.addAsResource("test-persistence.xml", ArchivePaths.create("META-INF/persistence.xml"))
.addAsResource("META-INF/application.properties", ArchivePaths.create("META-INF/application.properties"))
.addAsResource("datasets/", ArchivePaths.create("datasets/"))
.addAsManifestResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));
System.out.println(war.toString(true));
return war;
}
#Inject
PersonDao personDao;
#Inject
MongoProducer producer;
#Test
public void injectionPointShouldBeNotNull() {
assertThat(personDao).isNotNull();
}
#Test
public void mongoProducerShouldBeNotNull() {
assertThat(producer).isNotNull();
}
#Test
#org.arquillian.ape.rdbms.UsingDataSet("datasets/persons.xml")
public void shouldFindAll() {
List<Person> messages = personDao.findAll();
assertThat(messages.size()).isEqualTo(1);
}
#Test
#UsingDataSet(locations = "/datasets/initialData.json")
public void shouldGetAllFromMongo() {
FindIterable<Document> documents = producer.getMongoClient().getDatabase("pandadb").getCollection("bears").find();
documents.forEach((Block<? super Document>) System.out::println);
}
}

How to test static method invokation in Android?

I have an Android activity and I want to write a unit test, which verifies that in onResume the activity checks whether the Internet is available.
public class MyActivity {
#Override
protected void onResume() {
super.onResume();
setContentView(R.layout.connect_to_server);
// Internet availability check
final IInternetAvailabilityChecker checker = InternetAvailabilityChecker.create(this);
if (!checker.isInternetAvailable())
{
Utils.showMessageBox(this, R.string.app_name,
R.string.internet_not_available);
return;
}
In the test, I want to verify that MyActiviy.onResume calls the InternetAvailabilityChecker.create method.
How can I do it (with any free mocking framework compatible with Android) ?
I tried to use PowerMock for this (see example below), but when I try to run the test, I get errors like MockTest.java:7: package org.powermock.core.classloader.annotations does not exist.
Maven:
<properties>
<powermock.version>1.5.1</powermock.version>
</properties>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
Unit test:
#RunWith(PowerMockRunner.class)
#PrepareForTest( { InternetAvailabilityChecker.class })
public class MyActivityPowerMockTest {
#Test
#Ignore
public void test()
{
final IInternetAvailabilityChecker checker = mock(IInternetAvailabilityChecker.class);
when(checker.isInternetAvailable()).thenReturn(false);
mockStatic(InternetAvailabilityChecker.class);
expect(InternetAvailabilityChecker.create(any(Activity.class))).andReturn(checker);
replay(InternetAvailabilityChecker.class);
final MyActivity objectUnderTest = new MyActivity();
objectUnderTest.onResume();
// Verify that the method InternetAvailabilityChecker.create was called
verify(InternetAvailabilityChecker.class);
// TODO: Verify that Utils.showMessageBox has been invoked
}
}
You appear to be missing a Maven dependency. According to this query the annotations are supplied by:
org.powermock / powermock-core
org.powermock / powermock-easymock-single-jar-release-full
org.powermock / powermock-mockito-single-jar-release-full

Categories

Resources