Asynchronous Swift Testing of Protocols with XCTestCase - unit-testing

I'm trying to write a REST Api class in swift and test it. I was attempting to follow the methodology in: how to test asynchronous methods Swift but I seem to have run into an issue.
Client/RestInterface.swift
import Foundation
protocol RestSearchProtocol {
func didRecieveResponse(results: NSDictionary)
}
public class RestInterface : NSObject {
// lots of code we don't care about ...
}
ClientTests/RestInterfaceTests.swift
import UIKit
import XCTest
import Client
class RestInterfaceTests: XCTestCase, RestSearchProtocol {
// ... rest of the test file
I'm getting an undeclared type error.
Any suggestions as how to make this work?
As a side note - if i take the RestInterfaceTests class and put it at the end of RestInterface.swift it seems to find the protocol, but XCTestCase is now undeclared

It appears i was missing the public identifier:
import Foundation
public protocol RestSearchProtocol {
func didRecieveResponse(results: NSDictionary)
}
public class RestInterface : NSObject {
// lots of code we don't care about ...
}
has solved the problem

use
#testable import Client
You don't need to set your types as public anymore!

Related

How to inject app.context into Loopback 4 controller

I cannot find any suitable example on how to inject an app.context object into a Loopback 4 controller being in a separate file
This inline example from the documentation works fine
import {inject} from '#loopback/context';
import {Application} from '#loopback/core';
const app = new Application();
app.bind('defaultName').to('John');
export class HelloController {
constructor(#inject('defaultName') private name: string) {}
greet(name?: string) {
return `Hello ${name || this.name}`;
}
}
but I cannot find a way to obtain the same having my controller in a separate file.
I am trying to do something like this:
export class PingController {
constructor(#inject(app.name) private name: string)
app.name being a simple binding in my app-context.
Solution was quite simple.
Since all context values on app level is available throughout the application, no reference to app is required.
I just needed to replace (app.name) with ('name') in the constructor injection.

JMockit can't find EJB, get NoSuchMethodException instead

Trying to mock a MessageDriven bean but have trouble getting the #EJB to be injected. The #Resource works "fine" (doesn't break it at least).
If I comment out the #EJB line in MyMDB it works fine. Probably an easy thing I missed, but I can't find it...
Also I found that replacing #EJB with #Inject will make it work, but I want to know why it doesn't work with #EJB since we have a lot of code like that.
Using JDK7 and JMockit v1.39
The error I get is:
java.lang.RuntimeException: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy7.lookup()
Caused by: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy7.lookup()
at java.lang.Class.getMethod(Class.java:1678)
MyMDB.java:
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageListener;
#MessageDriven(activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "/queue/myqueue") })
public class MyMDB implements MessageListener {
#Resource(mappedName = "java:/JmsBT")
ConnectionFactory connectionFactory;
#EJB
ParConfigI parConfig;
#Override
public void onMessage(Message message) {
System.out.println("onMessage called");
}
}
MyMDBTest.java
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import org.junit.Test;
import mockit.Injectable;
import mockit.Mocked;
import mockit.Tested;
public class MyMDBTest {
#Tested
MyMDB sut;
#Injectable
ConnectionFactory jmsbt;
#Injectable
ParConfigI parConfigI;
#Mocked
Message mockedMessage;
#Test
public void testSmall() {
sut.onMessage(mockedMessage);
}
}
ParConfigI.java
import javax.ejb.Local;
#Local
public interface ParConfigI {
public void testmethod();
}
The problem is that JMockit attempts to read the lookup attribute on the #EJB annotation, but this attribute only exists in EJB 3.1+ (added in Java EE 6), not in EJB 3.0 (Java EE 5). Hence the NoSuchMethodException.
JMockit 1.40 is fixing this, but Java EE 6 has been available since early 2010. So, upgrading from the ancient Java EE 5 would also solve the problem.

Make Logback throw exception on ERROR level log events

When running unit tests, I'd like to fail any tests during which ERROR level message is logged. What would be the easiest way to achieve this using SLF4J/Logback? I'd like to avoid writing my own ILoggerFactory implementation.
I tried writing a custom Appender, but I cannot propagate exceptions through the code that's calling the Appender, all exceptions from Appender get caught there.
The key is to write a custom appender. You don't say which unit testing framework you use, but for JUnit I needed to do something similar (it was a little more complex than just all errors, but basically the same concept), and created a JUnit #Rule that added my appender, and the appender fails the test as needed.
I place my code for this answer in the public domain:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.rules.ExternalResource;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.fail;
/**
* A JUnit {#link org.junit.Rule} which attaches itself to Logback, and fails the test if an error is logged.
* Designed for use in some tests, as if the system would log an error, that indicates that something
* went wrong, even though the error was correctly caught and logged.
*/
public class FailOnErrorLogged extends ExternalResource {
private FailOnErrorAppender appender;
#Override
protected void before() throws Throwable {
super.before();
final LoggerContext loggerContext = (LoggerContext)(LoggerFactory.getILoggerFactory());
final Logger rootLogger = (Logger)(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME));
appender = new FailOnErrorAppender();
appender.setContext(loggerContext);
appender.start();
rootLogger.addAppender(appender);
}
#Override
protected void after() {
appender.stop();
final Logger rootLogger = (Logger)(LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME));
rootLogger.detachAppender(appender);
super.after();
}
private static class FailOnErrorAppender extends AppenderBase<ILoggingEvent> {
#Override
protected void append(final ILoggingEvent eventObject) {
if (eventObject.getLevel().isGreaterOrEqual(Level.ERROR)) {
fail("Error logged: " + eventObject.getFormattedMessage());
}
}
}
}
An example of usage:
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExampleTest {
private static final Logger log = LoggerFactory.getLogger(ExampleTest.class);
#Rule
public FailOnErrorLogged failOnErrorLogged = new FailOnErrorLogged();
#Test
public void testError() {
log.error("Test Error");
}
#Test
public void testInfo() {
log.info("Test Info");
}
}
The testError method fails and the testInfo method passes. It works the same if the test calls the real class-under-test that logs an error as well.
Logging frameworks are generally designed not to throw any exceptions to the user. Another option (in addition to Raedwald's answer) would be to create a custom appender that sets a static boolean flag to true when an ERROR message is logged, reset this flag in a setup method and check it in a teardown method (or create a JUnit rule to reset/check the flag).
So, you want to fail your test case if any error reporting message of the logger is called.
Use dependency injection to associate the code to be tested with the logger it should use.
Implement a test double that implements the SLF4J logger interface, and which does nothing for most methods, but throws an AssertionError for the error logging methods.
In the set-up part of the test case, inject the test double.

Grails Unit Test

I have unit test wich extends GrailsUnitTestCase :
import grails.test.GrailsUnitTestCase
class HttpdParserSpec extends GrailsUnitTestCase {
}
However I saw in Grails documentation that is deprecated.
I tried to use the following :
import grails.test.mixin.TestFor
#TestFor(HttpdParser)
class HttpdParserSpec {
}
I obtain the following error :
Cannot add Domain class [class fr.edu.toolprod.parser.HttpdParser]. It
is not a Domain!
It's true.It's not a Domain class.I only want test a simple class HttpdParser.
What am I doing wrong ?
So how to make a simple unit test ? Have you an example ?
Don't use the TestFor annotation. Just write a unit test as you normally would. TestFor is useful for rigging up Grails artifacts and relevant elements of the environment for unit testing them.
class HttpdParserSpec extends spock.lang.Specification {
void 'test something'() {
when:
def p = new HttpdParser()
p.doSomething()
then:
p.someValue == 42
}
}
You can also just use the #TestMixin annotation with the GrailsUnitTestCaseMixin like this:
import grails.test.mixin.support.GrailsUnitTestMixin
import grails.test.mixin.TestMixin
#TestMixin(GrailsUnitTestMixin)
class MyTestClass {}

HaxePunk: Nothing is rendering when exporting to C++

So I'm making a game with Haxe and Haxepunk. Fine. Except that when I export to C++, nothing is rendering! I posted this previously on the Haxepunk boards, so more info can be found here. Here's an excerpt from the Haxepunk thread;
I can still compile it just fine, but nothing in the game is actually rendering except for the background color I defined. The console still works and renders fine, though. The HaxePunk console tells me Atlases using BitmapData will not be managed.
I'm using Ash's component-entity system, and I'm not using Haxe's Entities. The relevant objects have a Visible component attached to them, which looks like this;
package game.component;
import com.haxepunk.Graphic;
import com.haxepunk.graphics.Image;
class Visible {
public var image(default, default) : Graphic;
public function new() {
this.image = Image.createRect(16, 16, 0xFF0000);
}
}
And this is the associated rendering system;
package game.system;
import ash.core.Engine;
import ash.core.Entity;
import ash.core.System;
import ash.tools.ListIteratingSystem;
import com.haxepunk.HXP;
import Constants;
import game.component.Positionable;
import game.component.Visible;
import game.node.RenderNode;
class RenderingSystem extends ListIteratingSystem<RenderNode> {
public function new() {
super(RenderNode, this.updateNode);
}
private function updateNode(node:RenderNode, time:Float) : Void {
node.renderable.image.render(HXP.buffer, node.position.position, Constants.ORIGIN);
}
}
Any tips?
If you are using buffer rendering in C++ you'll need to set the render mode inside the constructor. This is because the Engine constructor is the only place a screen buffer is created. Unfortunately the API docs don't clearly explain this.
class Main extends Engine
{
public function new()
{
super(0, 0, 60, false, RenderMode.BUFFER);
}
}