I have a JUnit test that I run on one class, but I recently wrote an emulated version for GWT. Since the specification is the same, I would like to use the same test case, but I want it to run in the GWT environment, which would typically be accomplished by extending GWTTestCase.
I really want to avoid any copy/paste nonsense, because there are likely to be added tests in the future, which I should not be burdened with copying later.
How can I import/inherit my standard unit test to be run as either a regular test case or a GWT test case?
I have found the solution to this problem.
If you extend the original test with GWTTestCase, you can override getModuleName to return null. This tells GWTTestCase to run as a normal pure java test (no translation at all).
You can then extend this test case with one that overrides getModuleName to return a module name, and the same tests will be run with translation.
Basically:
public class RegularTest extends GWTTestCase {
#Override
public String getModuleName() { return null; }
public void testIt() {...}
}
...and the GWT version...
public class GwtTest extends RegularTest {
#Override
public String getModuleName() { return "some.module"; }
}
The downside to this is that it forces you to use JUnit3 style tests, which I find a little annoying, but it beats the alternative.
I think there is no easy way .. But you can extract an interface of your junit test, gwt test case and junit test case implements this interface. You can create a third class for implementation, all test call methods of gwt test case and junit test are delegated to this implementation class.
public interface IRegularTest {
public void testSomething();
public void testSomething2();
}
public class RegularTestImpl implements IRegularTest {
public void testSomething(){
// actual test code
}
public void testSomething2(){
// actual test code
}
}
public class RegularTest extends TestCase implements IRegularTest {
IRegularTest impl = new RegularTestImpl();
public void testSomething(){
impl.testSomething
}
public void testSomething2(){
}
}
public class GwtTest extends TestCase implements IRegularTest {
IRegularTest impl = new RegularTestImpl();
public void testSomething(){
impl.testSomething
}
public void testSomething2(){
}
}
Related
I want to unit test Camel code using ScalaTest and the FunSpec test style.
To do so, I need to extend from both FunSpec and CamelTestSupport. However, both these are classes and at least one needs to be a trait in order to do this in Scala. For example, this does not work:
class MySpec extends FunSpec with CamelTestSupport {}
Note: It appears that many online references to FunSpec suggest it is a trait, but it is a class in scalatest_2.11-3.0.0-M15.
How can I use ScalaTest FunSpec to test Camel?
The same test written using JUnit would look as follows:
public class DataLakeEventListenerRouteIT extends CamelTestSupport {
#Autowired
private MyRouteBuilder myRouteBuilder;
private MockEndpoint myEndpointMock;
#Override
public boolean isUseAdviceWith() {
return true;
}
#Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry registry = super.createRegistry();
//do some required bindings here
return registry;
}
#Before
public void startup() throws Exception {
AdviceWithRouteBuilder mock = new AdviceWithRouteBuilder() {
public void configure() throws Exception {
mockEndpointsAndSkip(myRouteBuilder.MY_ROUTE_URI);
}
};
context.addRoutes(myRouteBuilder);
context.getRouteDefinition(myRouteBuilder.MY_ROUTE_ID)
.adviceWith(context, mock);
myEndpointMock = getMockEndpoint(
"mock:" + myRouteBuilder.MY_ROUTE_URI);
}
#Test
public void timerRouteShouldSendMessage() throws Exception {
// Arrange
context.start();
myEndpointMock.expectedMessageCount(1);
myEndpointMock.assertIsSatisfied();
context.stop();
}
}
Well, it turns out to straightforward. ScalaTest offers a trait equivalent of FunSpec called FunSpecLike. Declare the test like so:
class StoreSVSFileRouteSpec extends CamelTestSupport with FunSpecLike {}
I need to run inner class test cases from eclipse using Junit4. I understand that there is org.junit.runners.Enclosed that is intended to serve this purpose. It works well for "plain" unit test i.e. without the need for spring context configuration.
For my case, give sample code below, Adding another annotation of Enclosed does not work since there is a conflict of both SpringJUnit4ClassRunner and Enclosed test runners. How can I solve this problem ?
Note: Kindly ignore any basic spelling mistake/basic import issues in the below example since I tried to cook up from my actual use-case.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/unit-test-context.xml"})
public class FooUnitTest {
// Mocked dependency through spring context
#Inject
protected DependentService dependentService;
public static class FooBasicScenarios extends FooUnitTest{
#Test
public void testCase1 {
.....
List<Data> data = dependentService.getData();
.....
}
}
public static class FooNeagativeScenarios extends FooUnitTest{
#Test
public void testCase1 {
.....
List<Data> data = dependentService.getData();
.....
}
}
}
}
FooUnitTest is a container, you cannot use it as a superclass.
You need to move all your spring-code to Scenario-classes. And use #RunWith(Enclosed.class). For example, with abstract superclass
#RunWith(Enclosed.class)
public class FooUnitTest {
#ContextConfiguration(locations = { "/unit-test-context.xml"})
protected abstract static class BasicTestSuit {
// Mocked dependency through spring context
#Inject
protected DependentService dependentService;
}
#RunWith(SpringJUnit4ClassRunner.class)
public static class FooBasicScenarios extends BasicTestSuit {
#Test
public void testCase1 {
.....
List<Data> data = dependentService.getData();
.....
}
}
#RunWith(SpringJUnit4ClassRunner.class)
public static class FooNeagativeScenarios extends BasicTestSuit {
#Test
public void testCase1 {
.....
List<Data> data = dependentService.getData();
.....
}
}
}
Of course you can declare all dependencies in each Scenario-class, in that case there is no necessary in abstract superclass.
I want to run the same JUnit tests for different interface implementations. I found a nice solution with the #Parameter option:
public class InterfaceTest{
MyInterface interface;
public InterfaceTest(MyInterface interface) {
this.interface = interface;
}
#Parameters
public static Collection<Object[]> getParameters()
{
return Arrays.asList(new Object[][] {
{ new GoodInterfaceImpl() },
{ new AnotherInterfaceImpl() }
});
}
}
This test would be run twice, first with the GoodInterfaceImpl then with the AnotherInterfaceImpl class. But the problem is I need for most of the testcases a new object. A simplified example:
#Test
public void isEmptyTest(){
assertTrue(interface.isEmpty());
}
#Test
public void insertTest(){
interface.insert(new Object());
assertFalse(interface.isEmpty());
}
If the isEmptyTest is run after the insertTest it fails.
Is there an option to run automatically each testcase with a new instance of an implementation?
BTW: Implementing a clear() or reset()-method for the interface is not really an options since I would not need it in productive code.
Here is another approach with the Template Method pattern:
The interface-oriented tests go into the base class:
public abstract class MyInterfaceTest {
private MyInterface myInterface;
protected abstract MyInterface makeContractSubject();
#Before
public void setUp() {
myInterface = makeContractSubject();
}
#Test
public void isEmptyTest(){
assertTrue(myInterface.isEmpty());
}
#Test
public void insertTest(){
myInterface.insert(new Object());
assertFalse(myInterface.isEmpty());
}
}
For each concrete class, define a concrete test class:
public class GoodInterfaceImplTest extends MyInterfaceTest {
#Override
protected MyInterface makeContractSubject() {
// initialize new GoodInterfaceImpl
// insert proper stubs
return ...;
}
#Test
public void additionalImplementationSpecificStuff() {
...
}
}
A slight advantage over #Parameter is that you get the name of the concrete test class reported when a test fails, so you know right away which implementation failed.
Btw, in order for this approach to work at all, the interface must be designed in a way which allows testing by the interface methods only. This implies state-based testing -- you cannot verify mocks in the base test class. If you need to verify mocks in implementation-specific tests, these tests must go into the concrete test classes.
Create a factory interface and implementations, possibly only in your test hierarchy if you don't need such a thing in production, and make getParameters() return a list of factories.
Then you can invoke the factory in a #Before annotated method to get a new instance of your actual class under test for each test method run.
Just in case somebody reaches here(like I did), looking for testing multiple implementations of the same interface in .net you could see one of the approaches that I was using in one of the projects here
Below is what we are following in short
The same test project dll is run twice using vstest.console, by setting an environment variable. Inside the test, (either in the assembly initialize or test initialize) register the appropriate implementations into a IoC container, based on the environment variable value.
In Junit 5 you could do:
#ParameterizedTest
#MethodSource("myInterfaceProvider")
void test(MyInterface myInterface) {}
static Stream<MyInterface> myInterfaceProvider() {
return Stream.of(new ImplA(), new ImplB());
}
interface MyInterface {}
static class ImplA implements MyInterface {}
static class ImplB implements MyInterface {}
We currently have a suite of integration tests that run via MbUnit test suites. We are in the process of refactoring much of the code to use an IOC framework (StructureMap).
I'd like to configure/initialize the container ONCE when the MBUnit test runner fires up, using the same registry code that we use in production.
Is there a way of achieving this in MbUnit?
(EDIT) The version of MbUnit is 2.4.197.
Found it. The AssemblyCleanup attribute.
http://www.testingreflections.com/node/view/639
I understand that you want to spin up only one container for your entire test run and have it be the container used across test suite execution. The MBUnit docs make it look like you might be able to use a TestSuiteFixture and TestSuiteFixtureSetup to accomplish about what you want.
I wanted to speak from the point of view of a StructureMap user and Test Driven Developer.
We rarely use containers in our test suites unless we are explicitly testing pulling things out of the container. When this is necessary I use the an abstract test base class below (warning we use NUnit):
[TestFixture]
public abstract class with_container
{
protected IContainer Container;
[TestFixtureSetUp]
public void beforeAll()
{
Container = new ServiceBootstraper().GetContainer();
Container.AssertConfigurationIsValid();
}
}
public class Bootstraper
{
public Bootstraper()
{
ObjectFactory.Initialize(x =>
{
//register stuff here
});
}
public IContainer GetContainer()
{
return ObjectFactory.Container;
}}
I would recommend for normal tests that you skip the normal container and just use the automocking container included with StructureMap. Here is another handy abstract test base class we use.
public abstract class Context<T> where T : class
{
[SetUp]
public void Setup()
{
_services = new RhinoAutoMocker<T>(MockMode.AAA);
OverrideMocks();
_cut = _services.ClassUnderTest;
Given();
}
public RhinoAutoMocker<T> _services { get; private set; }
public T _cut { get; private set; }
public SERVICE MockFor<SERVICE>() where SERVICE : class
{
return _services.Get<SERVICE>();
}
public SERVICE Override<SERVICE>(SERVICE with) where SERVICE : class
{
_services.Inject(with);
return with;
}
public virtual void Given()
{
}
public virtual void OverrideMocks()
{
}
}
and here is a basic test using this context tester:
[TestFixture]
public class communication_publisher : Context<CommunicationPublisher>
{
[Test]
public void should_send_published_message_to_endpoint_retrieved_from_the_factory()
{
var message = ObjectMother.ValidOutgoingCommunicationMessage();
_cut.Publish(message);
MockFor<IEndpoint>().AssertWasCalled(a => a.Send(message));
}
}
Sorry if this is not exactly what you wanted. Just these techniques work very well for us and I wanted to share.
If I have the following code:
[TestFixture]
public class MyBaseTest
{
protected ISessionManager _sessionManager;
[SetUp]
public void SetUp() { /* some code that initializes _sessionManager */ }
}
[TestFixture]
public class MyDerivedTest : MyBaseTest
{
IBlogRepository _repository;
[SetUp]
public void SetUp() { /* some code that initializes _repository */ }
[Test]
public void BlogRepository_TestGoesHere() { /* some tests */ }
}
...NUnit doesn't call the base SetUp routine. This is expected, and I don't have a problem with it in itself. I can get the derived SetUp to call the base SetUp first, like this:
[TestFixture]
public class MyDerivedTest : MyBaseTest
{
IBlogRepository _repository;
[SetUp]
public new void SetUp()
{
base.SetUp();
/* some code that initializes _repository */
}
This is ugly. If it was a constructor, I wouldn't have to.
I could use the "template method" pattern, and have the following:
public void MyBaseTest
{
abstract void SetUp();
[SetUp]
public void BaseSetUp()
{
/* base initialization */
SetUp(); // virtual call
}
}
I'm not particularly fond of this, either.
What do you do when their test classes need SetUp, and they're derived from another class that also needs SetUp?
You have to call the method directly.
[SetUp]
public void DerivedSetUp()
{
base.BaseSetUp();
// Do something else
}
Edit: I haven't tried it, but perhaps a partial method might work too. I'd prefer to do the above though.
Edit2: I've just tried using partial methods. It didn't work. Even if it did, I think it's still going to be easier to call the base class.
You have the base class explicitly. Given that NUnit uses the [Setup] attribute to mark up test setup, I tink this is "the right thing" to do for NUnit, because it follows the usual language rules.
Sure, NUnit could search the base classes, and call their Setup functions automagically, but I think this would be rather surprising for most people.
There is however at least one unit testing framework that uses constructors for setup: xUnit.Net. Here, the base class setup is called automatically, because this is how constructors in C# behave.
(Note, though, that xUnit.Net recommends again using test setup.)
It looks like you want the setup to be run once before any testing starts, not once before each test is run. The annotation [SetUp] makes the method run once before each test in your fixture is run. [SetUp] is not inherited.
The annotation you want to use is [TestFixtureSetUp] which is run only once, before any of the tests in a fixture are run. This is inherited in the way that you would expect. :)
See the TextFixtureSetUp docs
An approach that I use that I learned in the TDD FireStarter in Tampa was to have the setup method in the base class and then to have a virtual method in the base class called observe. This method is then called in the base class at the end of the setup method.
Then what you do is in the new class that derives from the base class you will override the observe method. The trick in this scenario is you want to execute the Setup method of the base class and the child class does not have a Setup method. The reason for this is the code that you have in the observe method are only those additional things you need for the child test class.
This approach works well for me, but one gotcha is that the test runner will want to execute the base class tests, so what I do to get around that is to move the Tests from the base class into a new class that derives from the base if I have any.
The following works in MbUnit. It may work in NUnit as well.
[TestFixture]
public abstract class Base {
[SetUp]
public virtual void SetUp() {
//Some stuff.
}
}
public class Derived : Base {
public override void SetUp() {
base.SetUp();
//Some more stuff.
}
[Test]
public virtual void Object_WhenInACertainState_WhenAMethodIsCalled_Throws() {
//Create and set state on the object.
//Call the method.
//Assert the method threw.
}
}