Search Results

Search found 12476 results on 500 pages for 'unit testing'.

Page 15/500 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • .NET unit test runner outputting FaultException.Detail

    - by Adam
    Hello, I am running some unit tests on a WCF service. The service is configured to include exception details in the fault response (with the following in my service configuration file). <serviceDebug includeExceptionDetailInFaults="true" /> If a test causes an unhandled exception on the server the fault is received by the client with a fully populated server stack trace. I can see this by calling the exception's ToString() method. The problem is that this doesn't seem to be output by any of the test runners that I have tried (xUnit, Gallio, MSTest). They appear to just output the Message and the StackTrace properties of the exception. To illustrate what I mean, the following unit test run by MSTest would output three sections: Error Message Error Stack Trace Standard Console Output (contains the information I would like, e.g. "Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: ..." try { service.CallMethodWhichCausesException(); } catch (Exception ex) { Console.WriteLine(ex); // this outputs the information I would like throw; } Having this information will make the initial phase of testing and deployment a lot less painful. I know I can just wrap each unit test in a generic exception handler and write the exception to the console and rethrow (as above) within all my unit tests but that seems a very long-winded way of achieving this (and would look pretty awful). Does anyone know if there's any way to get this information included for free whenever an unhandled exception occurs? Is there a setting that I am missing? Is my service configuration lacking in proper fault handling? Perhaps I could write some kind of plug-in / adapter for some unit testing framework? Perhaps theres a different unit testing framework which I should be using instead! My actual set-up is xUnit unit tests executed via Gallio for the development environment, but I do have a separate suite of "smoke tests" written which I would like to be able to have our engineers run via the xUnit GUI test runner (or Gallio or whatever) to simplify the final deployment. Thanks. Adam

    Read the article

  • Any suggestions for testing extjs code in a browser, preferably with selenium?

    - by mm2001
    We've been using selenium with great success to handle high-level website testing (in addition to extensive python doctests at a module level). However now we're using extjs for a lot of pages and its proving difficult to incorporate Selenium tests for the complex components like grids. Has anyone had success writing automated tests for extjs-based web pages? Lots of googling finds people with similar problems, but few answers. Thanks!

    Read the article

  • Testing the context in asp.net mvc

    - by user252160
    I got pretty experienced with testing controllers, my question here is though, aren't we supposed to test the data context as well, and how ? I mean, there are a lot of relationships and constraints coming from the DB that simply testing controllers does not cover. On the other hand, testing against the DB is not considered a good practice - what then ? Simply testing without db.SubmitChanges() or what ?

    Read the article

  • Gradle + Robolectric: Where do I put the file org.robolectric.Config.properties?

    - by Rob Hawkins
    I'm trying to setup a test using Robolectric to click on a menu button in this repository. Basic Robolectric tests will run, but I'm not able to run any project-specific test using resources because it says it can't find my AndroidManifest.xml. After running ../gradlew clean check, here's the standard output from the Robolectric html file: WARNING: No manifest file found at ./AndroidManifest.xml.Falling back to the Android OS resources only. To remove this warning, annotate your test class with @Config(manifest=Config.NONE). I found these instructions which indicate I should create an org.robolectric.Config.properties file, but I'm not sure where to put it. I've tried everywhere, pretty much, and despite moving the file, the path in the error message is always the same as above (./AndroidManifest.xml). This makes me think the build process has never picked up the settings in the file org.robolectric.Config.properties. I also tried the @Config(manifest="") directive but this gave me a cannot find symbol error. If I move the AndroidManifest.xml into my project directory, then I get an error about it not being able to find the path ./res/values and I wasn't able to resolve that either. Any ideas? Update 1 Thanks Eugen, I'm now using @RunWith(RobolectricGradleTestRunner.class) instead of @RunWith(RobolectricTestRunner). Now I get a different error, still occurring on the same line of my BasicTest.java KeywordList keywordList = Robolectric.buildActivity(KeywordList.class).create().get(); Below are results from the standard error, standard output, and "failed tests" tab in the Robolectric test report: Note: I also tried substituting in a jar built from the latest Robolectric updates, robolectric-2.2-SNAPSHOT.jar, but still got an error. Standard Error WARNING: no system properties value for ro.build.date.utc Standard Output DEBUG: Loading resources for net.frontlinesms.android from ~/workspace-studio/frontlinesms-for-android/FrontlineSMS/build/res/all/debug... DEBUG: Loading resources for android from jar:~/.m2/repository/org/robolectric/android-res/4.1.2_r1_rc/android-res-4.1.2_r1_rc-real.jar!/res... INFO: no id mapping found for android:drawable/scrollbar_handle_horizontal; assigning ID #0x1140002 INFO: no id mapping found for android:drawable/scrollbar_handle_vertical; assigning ID #0x1140003 INFO: no id mapping found for android:color/highlighted_text_dark; assigning ID #0x1140004 INFO: no id mapping found for android:color/hint_foreground_dark; assigning ID #0x1140005 INFO: no id mapping found for android:color/link_text_dark; assigning ID #0x1140006 INFO: no id mapping found for android:color/dim_foreground_dark_disabled; assigning ID #0x1140007 INFO: no id mapping found for android:color/dim_foreground_dark; assigning ID #0x1140008 INFO: no id mapping found for android:color/dim_foreground_dark_inverse_disabled; assigning ID #0x1140009 INFO: no id mapping found for android:color/dim_foreground_dark_inverse; assigning ID #0x114000a INFO: no id mapping found for android:color/bright_foreground_dark_inverse; assigning ID #0x114000b INFO: no id mapping found for android:layout/text_edit_paste_window; assigning ID #0x114000c INFO: no id mapping found for android:layout/text_edit_no_paste_window; assigning ID #0x114000d INFO: no id mapping found for android:layout/text_edit_side_paste_window; assigning ID #0x114000e INFO: no id mapping found for android:layout/text_edit_side_no_paste_window; assigning ID #0x114000f INFO: no id mapping found for android:layout/text_edit_suggestion_item; assigning ID #0x1140010 Failed Tests android.view.InflateException: XML file ~/workspace-studio/frontlinesms-for-android/FrontlineSMS/build/res/all/debug/layout/rule_list.xml line #-1 (sorry, not yet implemented): Error inflating class net.frontlinesms.android.ui.view.ActionBar at android.view.LayoutInflater.createView(LayoutInflater.java:613) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java:352) at org.robolectric.tester.android.view.RoboWindow.setContentView(RoboWindow.java:82) at org.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:272) at android.app.Activity.setContentView(Activity.java) at net.frontlinesms.android.activity.KeywordList.onCreate(KeywordList.java:70) at android.app.Activity.performCreate(Activity.java:5008) at org.fest.reflect.method.Invoker.invoke(Invoker.java:112) at org.robolectric.util.ActivityController$1.run(ActivityController.java:119) at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256) at org.robolectric.util.ActivityController.create(ActivityController.java:114) at org.robolectric.util.ActivityController.create(ActivityController.java:126) at net.frontlinesms.android.BasicTest.setUp(BasicTest.java:30) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:241) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355) at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:680) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_createView(LayoutInflater.java:587) at android.view.LayoutInflater.createView(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_createViewFromTag(LayoutInflater.java:687) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.rInflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:352) at android.view.LayoutInflater.inflate(LayoutInflater.java) at org.robolectric.tester.android.view.RoboWindow.setContentView(RoboWindow.java:82) at org.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:272) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.robolectric.bytecode.ShadowWrangler$ShadowMethodPlan.run(ShadowWrangler.java:455) at android.app.Activity.setContentView(Activity.java) at net.frontlinesms.android.activity.KeywordList.onCreate(KeywordList.java:70) at android.app.Activity.$$robo$$Activity_c57b_performCreate(Activity.java:5008) at android.app.Activity.performCreate(Activity.java) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.fest.reflect.method.Invoker.invoke(Invoker.java:112) at org.robolectric.util.ActivityController$1.run(ActivityController.java:119) at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256) at org.robolectric.util.ActivityController.create(ActivityController.java:114) at org.robolectric.util.ActivityController.create(ActivityController.java:126) at net.frontlinesms.android.BasicTest.setUp(BasicTest.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:241) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) ... 7 more Caused by: android.view.InflateException: XML file ~/workspace-studio/frontlinesms-for-android/FrontlineSMS/build/res/all/debug/layout/actionbar.xml line #-1 (sorry, not yet implemented): Error inflating class android.widget.ProgressBar at android.view.LayoutInflater.createView(LayoutInflater.java:613) at org.robolectric.shadows.RoboLayoutInflater.onCreateView(RoboLayoutInflater.java:38) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at net.frontlinesms.android.ui.view.ActionBar.<init>(ActionBar.java:65) at android.view.LayoutInflater.createView(LayoutInflater.java:587) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java:352) at org.robolectric.tester.android.view.RoboWindow.setContentView(RoboWindow.java:82) at org.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:272) at android.app.Activity.setContentView(Activity.java) at net.frontlinesms.android.activity.KeywordList.onCreate(KeywordList.java:70) at android.app.Activity.performCreate(Activity.java:5008) at org.fest.reflect.method.Invoker.invoke(Invoker.java:112) at org.robolectric.util.ActivityController$1.run(ActivityController.java:119) at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256) at org.robolectric.util.ActivityController.create(ActivityController.java:114) at org.robolectric.util.ActivityController.create(ActivityController.java:126) at net.frontlinesms.android.BasicTest.setUp(BasicTest.java:30) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:241) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103) ... 7 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_createView(LayoutInflater.java:587) at android.view.LayoutInflater.createView(LayoutInflater.java) at org.robolectric.shadows.RoboLayoutInflater.onCreateView(RoboLayoutInflater.java:38) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_onCreateView(LayoutInflater.java:660) at android.view.LayoutInflater.onCreateView(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_createViewFromTag(LayoutInflater.java:685) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.rInflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_rInflate(LayoutInflater.java:749) at android.view.LayoutInflater.rInflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java) at net.frontlinesms.android.ui.view.ActionBar.<init>(ActionBar.java:65) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_createView(LayoutInflater.java:587) at android.view.LayoutInflater.createView(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_createViewFromTag(LayoutInflater.java:687) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.rInflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java) at android.view.LayoutInflater.$$robo$$LayoutInflater_1d1f_inflate(LayoutInflater.java:352) at android.view.LayoutInflater.inflate(LayoutInflater.java) at org.robolectric.tester.android.view.RoboWindow.setContentView(RoboWindow.java:82) at org.robolectric.shadows.ShadowActivity.setContentView(ShadowActivity.java:272) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.robolectric.bytecode.ShadowWrangler$ShadowMethodPlan.run(ShadowWrangler.java:455) at android.app.Activity.setContentView(Activity.java) at net.frontlinesms.android.activity.KeywordList.onCreate(KeywordList.java:70) at android.app.Activity.$$robo$$Activity_c57b_performCreate(Activity.java:5008) at android.app.Activity.performCreate(Activity.java) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.fest.reflect.method.Invoker.invoke(Invoker.java:112) at org.robolectric.util.ActivityController$1.run(ActivityController.java:119) at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256) at org.robolectric.util.ActivityController.create(ActivityController.java:114) at org.robolectric.util.ActivityController.create(ActivityController.java:126) at net.frontlinesms.android.BasicTest.setUp(BasicTest.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24) at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:241) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy2.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) ... 7 more Caused by: java.lang.ClassCastException: org.robolectric.res.AttrData cannot be cast to org.robolectric.res.StyleData at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getParent(ShadowAssetManager.java:353) at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getAttrValue(ShadowAssetManager.java:336) at org.robolectric.shadows.ShadowResources.findAttributeValue(ShadowResources.java:259) at org.robolectric.shadows.ShadowResources.attrsToTypedArray(ShadowResources.java:188) at org.robolectric.shadows.ShadowResources.access$000(ShadowResources.java:51) at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:460) at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java) at android.content.Context.obtainStyledAttributes(Context.java:374) at android.view.View.__constructor__(View.java:3297) at org.fest.reflect.method.Invoker.invoke(Invoker.java:112) at org.robolectric.shadows.ShadowView.__constructor__(ShadowView.java:68) at android.view.View.<init>(View.java:3295) at android.widget.ProgressBar.<init>(ProgressBar.java:253) at android.widget.ProgressBar.<init>(ProgressBar.java:246) at android.widget.ProgressBar.<init>(ProgressBar.java:242) at android.view.LayoutInflater.createView(LayoutInflater.java:587) at org.robolectric.shadows.RoboLayoutInflater.onCreateView(RoboLayoutInflater.java:38) at android.view.LayoutInflater.onCreateView(LayoutInflater.java:660) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at net.frontlinesms.android.ui.view.ActionBar.<init>(ActionBar.java:65) at android.view.LayoutInflater.createView(LayoutInflater.java:587) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java:352) at org.robolectric.tester.android.view.RoboWindow.setContentView(RoboWindow.java:82) [truncated, hit stack overflow character limit...]

    Read the article

  • Writing Unit Tests for ASP.NET Web API Controller

    - by shiju
    In this blog post, I will write unit tests for a ASP.NET Web API controller in the EFMVC reference application. Let me introduce the EFMVC app, If you haven't heard about EFMVC. EFMVC is a simple app, developed as a reference implementation for demonstrating ASP.NET MVC, EF Code First, ASP.NET Web API, Domain-Driven Design (DDD), Test-Driven Development (DDD). The current version is built with ASP.NET MVC 4, EF Code First 5, ASP.NET Web API, Autofac, AutoMapper, Nunit and Moq. All unit tests were written with Nunit and Moq. You can download the latest version of the reference app from http://efmvc.codeplex.com/ Unit Test for HTTP Get Let’s write a unit test class for verifying the behaviour of a ASP.NET Web API controller named CategoryController. Let’s define mock implementation for Repository class, and a Command Bus that is used for executing write operations.  [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } The code block below provides the unit test for a HTTP Get operation. [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        The GetCategories method is provided below: private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } In the unit test method Get_All_Returns_AllCategory, we specify setup on the mocked type ICategoryrepository, for a call to GetCategoryWithExpenses method returns dummy data. We create an instance of the ApiController, where we have specified the Request property of the ApiController since the Request property is used to create a new HttpResponseMessage that will provide the appropriate HTTP status code along with response content data. Unit Tests are using for specifying the behaviour of components so that we have specified that Get operation will use the model type IEnumerable<CategoryWithExpense> for sending the Content data. The implementation of HTTP Get in the CategoryController is provided below: public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; } Unit Test for HTTP Post The following are the behaviours we are going to implement for the HTTP Post: A successful HTTP Post  operation should return HTTP status code Created An empty Category should return HTTP status code BadRequest A successful HTTP Post operation should provide correct Location header information in the response for the newly created resource. Writing unit test for HTTP Post is required more information than we write for HTTP Get. In the HTTP Post implementation, we will call to Url.Link for specifying the header Location of Response as shown in below code block. var response = Request.CreateResponse(HttpStatusCode.Created, category); string uri = Url.Link("DefaultApi", new { id = category.CategoryId }); response.Headers.Location = new Uri(uri); return response; While we are executing Url.Link from unit tests, we have to specify HttpRouteData information from the unit test method. Otherwise, Url.Link will get a null value. The code block below shows the unit tests for specifying the behaviours for the HTTP Post operation. [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } In the above code block, we have written two unit methods, Post_Category_Returns_CreatedStatusCode and Post_EmptyCategory_Returns_BadRequestStatusCode. The unit test method Post_Category_Returns_CreatedStatusCode  verifies the behaviour 1 and 3, that we have defined in the beginning of the section “Unit Test for HTTP Post”. The unit test method Post_EmptyCategory_Returns_BadRequestStatusCode verifies the behaviour 2. For extracting the data from response, we call Content.ReadAsStringAsync().Result of HttpResponseMessage object and deserializeit it with Json Convertor. The implementation of HTTP Post in the CategoryController is provided below: // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); } The unit test implementation for HTTP Put and HTTP Delete are very similar to the unit test we have written for  HTTP Get. The complete unit tests for the CategoryController is given below: [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        [Test] public void Get_CorrectCategoryId_Returns_Category() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(1);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);     var category = JsonConvert.DeserializeObject<CategoryWithExpense>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(1, category.CategoryId, "Got wrong number of Categories"); } [Test] public void Get_InValidCategoryId_Returns_NotFound() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(5);     // Assert     Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);            } [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } [Test] public void Put_Category_Returns_OKStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Put(category.CategoryId,category);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);    } [Test] public void Delete_Category_Returns_NoContentStatusCode() {     // Arrange              commandBus.Setup(c => c.Submit(It.IsAny<DeleteCategoryCommand >())).Returns(new CommandResult(true));     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act               var response = controller.Delete(1);     // Assert     Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);   } private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } }  The complete implementation for the Api Controller, CategoryController is given below: public class CategoryController : ApiController {       private readonly ICommandBus commandBus;     private readonly ICategoryRepository categoryRepository;     public CategoryController(ICommandBus commandBus, ICategoryRepository categoryRepository)     {         this.commandBus = commandBus;         this.categoryRepository = categoryRepository;     } public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; }   // GET /api/category/5 public HttpResponseMessage Get(int id) {     var category = categoryRepository.GetCategoryWithExpenses().Where(c => c.CategoryId == id).SingleOrDefault();     if (category == null)     {         return Request.CreateResponse(HttpStatusCode.NotFound);     }     return Request.CreateResponse(HttpStatusCode.OK, category); }   // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }   // PUT /api/category/5 public HttpResponseMessage Put(int id, CategoryModel category) {     if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         return Request.CreateResponse(HttpStatusCode.OK, category);     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }       // DELETE /api/category/5     public HttpResponseMessage Delete(int id)     {         var command = new DeleteCategoryCommand { CategoryId = id };         var result = commandBus.Submit(command);         if (result.Success)         {             return new HttpResponseMessage(HttpStatusCode.NoContent);         }             throw new HttpResponseException(HttpStatusCode.BadRequest);     } } Source Code The EFMVC app can download from http://efmvc.codeplex.com/ . The unit test project can be found from the project EFMVC.Tests and Web API project can be found from EFMVC.Web.API.

    Read the article

  • Is it bad practice to use Reflection in Unit testing?

    - by Sebi
    During the last years I always thought that in Java, Reflection is widely used during Unit testing. Since some of the variables/methods which have to be checked are private, it is somehow necessary to read the values of them. I always thought that the Reflection API is also used for this purpose. Last week i had to test some packages and therefore write some JUnit tests. As always i used Reflection to access private fields and methods. But my supervisor who checked the code wasn't really happy with that and told me that the Reflection API wasn't meant to use for such "hacking". Instead he suggested to modifiy the visibility in the production code. Is it really bad practice to use Reflection? I can't really believe that

    Read the article

  • Is it OK to have multiple asserts in a single unit test?

    - by Restuta
    I think that there are some cases when multiple assertions are needed (e.g. Guard Assertion), but in general I try to avoid this. What is your opinion? Please provide a real word examples when multiple asserts are really needed. Thanks! Edit In the comment to this great post Roy Osherove pointed to the OAPT project that is designed to run each assert in a single test. This is written on projects home page: Proper unit tests should fail for exactly one reason, that’s why you should be using one assert per unit test. And also Roy wrote in comments: My guideline is usually that you test one logical CONCEPT per test. you can have multiple asserts on the same object. they will usually be the same concept being tested.

    Read the article

  • Is it feasible and useful to auto-generate some code of unit tests?

    - by skiwi
    Earlier today I have come up with an idea, based upon a particular real use case, which I would want to have checked for feasability and usefulness. This question will feature a fair chunk of Java code, but can be applied to all languages running inside a VM, and maybe even outside. While there is real code, it uses nothing language-specific, so please read it mostly as pseudo code. The idea Make unit testing less cumbersome by adding in some ways to autogenerate code based on human interaction with the codebase. I understand this goes against the principle of TDD, but I don't think anyone ever proved that doing TDD is better over first creating code and then immediatly therafter the tests. This may even be adapted to be fit into TDD, but that is not my current goal. To show how it is intended to be used, I'll copy one of my classes here, for which I need to make unit tests. public class PutMonsterOnFieldAction implements PlayerAction { private final int handCardIndex; private final int fieldMonsterIndex; public PutMonsterOnFieldAction(final int handCardIndex, final int fieldMonsterIndex) { this.handCardIndex = Arguments.requirePositiveOrZero(handCardIndex, "handCardIndex"); this.fieldMonsterIndex = Arguments.requirePositiveOrZero(fieldMonsterIndex, "fieldCardIndex"); } @Override public boolean isActionAllowed(final Player player) { Objects.requireNonNull(player, "player"); Hand hand = player.getHand(); Field field = player.getField(); if (handCardIndex >= hand.getCapacity()) { return false; } if (fieldMonsterIndex >= field.getMonsterCapacity()) { return false; } if (field.hasMonster(fieldMonsterIndex)) { return false; } if (!(hand.get(handCardIndex) instanceof MonsterCard)) { return false; } return true; } @Override public void performAction(final Player player) { Objects.requireNonNull(player); if (!isActionAllowed(player)) { throw new PlayerActionNotAllowedException(); } Hand hand = player.getHand(); Field field = player.getField(); field.setMonster(fieldMonsterIndex, (MonsterCard)hand.play(handCardIndex)); } } We can observe the need for the following tests: Constructor test with valid input Constructor test with invalid inputs isActionAllowed test with valid input isActionAllowed test with invalid inputs performAction test with valid input performAction test with invalid inputs My idea mainly focuses on the isActionAllowed test with invalid inputs. Writing these tests is not fun, you need to ensure a number of conditions and you check whether it really returns false, this can be extended to performAction, where an exception needs to be thrown in that case. The goal of my idea is to generate those tests, by indicating (through GUI of IDE hopefully) that you want to generate tests based on a specific branch. The implementation by example User clicks on "Generate code for branch if (handCardIndex >= hand.getCapacity())". Now the tool needs to find a case where that holds. (I haven't added the relevant code as that may clutter the post ultimately) To invalidate the branch, the tool needs to find a handCardIndex and hand.getCapacity() such that the condition >= holds. It needs to construct a Player with a Hand that has a capacity of at least 1. It notices that the capacity private int of Hand needs to be at least 1. It searches for ways to set it to 1. Fortunately it finds a constructor that takes the capacity as an argument. It uses 1 for this. Some more work needs to be done to succesfully construct a Player instance, involving the creation of objects that have constraints that can be seen by inspecting the source code. It has found the hand with the least capacity possible and is able to construct it. Now to invalidate the test it will need to set handCardIndex = 1. It constructs the test and asserts it to be false (the returned value of the branch) What does the tool need to work? In order to function properly, it will need the ability to scan through all source code (including JDK code) to figure out all constraints. Optionally this could be done through the javadoc, but that is not always used to indicate all constraints. It could also do some trial and error, but it pretty much stops if you cannot attach source code to compiled classes. Then it needs some basic knowledge of what the primitive types are, including arrays. And it needs to be able to construct some form of "modification trees". The tool knows that it needs to change a certain variable to a different value in order to get the correct testcase. Hence it will need to list all possible ways to change it, without using reflection obviously. What this tool will not replace is the need to create tailored unit tests that tests all kinds of conditions when a certain method actually works. It is purely to be used to test methods when they invalidate constraints. My questions: Is creating such a tool feasible? Would it ever work, or are there some obvious problems? Would such a tool be useful? Is it even useful to automatically generate these testcases at all? Could it be extended to do even more useful things? Does, by chance, such a project already exist and would I be reinventing the wheel? If not proven useful, but still possible to make such thing, I will still consider it for fun. If it's considered useful, then I might make an open source project for it depending on the time. For people searching more background information about the used Player and Hand classes in my example, please refer to this repository. At the time of writing the PutMonsterOnFieldAction has not been uploaded to the repo yet, but this will be done once I'm done with the unit tests.

    Read the article

  • What is the most appropriate testing method in this scenario?

    - by Daniel Bruce
    I'm writing some Objective-C apps (for OS X/iOS) and I'm currently implementing a service to be shared across them. The service is intended to be fairly self-contained. For the current functionality I'm envisioning there will be only one method that clients will call to do a fairly complicated series of steps both using private methods on the class, and passing data through a bunch of "data mangling classes" to arrive at an end result. The gist of the code is to fetch a log of changes, stored in a service-internal data store, that has occurred since a particular time, simplify the log to only include the last applicable change for each object, attach the serialized values for the affected objects and return this all to the client. My question then is, how do I unit-test this entry point method? Obviously, each class would have thorough unit tests to ensure that their functionality works as expected, but the entry point seems harder to "disconnect" from the rest of the world. I would rather not send in each of these internal classes IoC-style, because they're small and are only made classes to satisfy the single-responsibility principle. I see a couple possibilities: Create a "private" interface header for the tests with methods that call the internal classes and test each of these methods separately. Then, to test the entry point, make a partial mock of the service class with these private methods mocked out and just test that the methods are called with the right arguments. Write a series of fatter tests for the entry point without mocking out anything, testing the entire functionality in one go. This looks, to me, more like "integration testing" and seems brittle, but it does satisfy the "only test via the public interface" principle. Write a factory that returns these internal services and take that in the initializer, then write a factory that returns mocked versions of them to use in tests. This has the downside of making the construction of the service annoying, and leaks internal details to the client. Write a "private" initializer that take these services as extra parameters, use that to provide mocked services, and have the public initializer back-end to this one. This would ensure that the client code still sees the easy/pretty initializer and no internals are leaked. I'm sure there's more ways to solve this problem that I haven't thought of yet, but my question is: what's the most appropriate approach according to unit testing best practices? Especially considering I would prefer to write this test-first, meaning I should preferably only create these services as the code indicates a need for them.

    Read the article

  • assistance with classifying tests

    - by amateur
    I have a .net c# library that I have created that I am currently creating some unit tests for. I am at present writing unit tests for a cache provider class that I have created. Being new to writing unit tests I have 2 questions These being: My cache provider class is the abstraction layer to my distributed cache - AppFabric. So to test aspects of my cache provider class such as adding to appfabric cache, removing from cache etc involves communicating with appfabric. Therefore the tests to test for such, are they still categorised as unit tests or integration tests? The above methods I am testing due to interacting with appfabric, I would like to time such methods. If they take longer than a specified benchmark, the tests have failed. Again I ask the question, can this performance benchmark test be classifed as a unit test? The way I have my tests set up I want to include all unit tests together, integration tests together etc, therefore I ask these questions that I would appreciate input on.

    Read the article

  • MS DPM 2007: Testing the Recovery for a Production Domain

    - by NewToDPM
    Hi everybody! MS DPM 2007 is a new technology in my company, and so am I to the product. We have a classic Microsoft domain with two DCs, Exchange 2007 and a couple Web/MS SQL servers. I have deployed DPM one month ago on the domain, and after fixing the various issues I got with the replicas inconsistence and adapting the schedule and retention range to the server storage pool size, I can say the backup system is working correctly (no errors) as of today. However, there is one problem: we did not attempt to restore from the backups yet, which is a big no-no of course. I'm not sure about the way I should handle this, my main concern being Exchange and the System State of the DCs. From my understanding, DPM can only protect AND restore data on a server which is part of the same domain as the backup server. If I restore the System State (containing Active Directory) and the Exchange Storage Groups on a testing server, I am afraid it would completely disturb the domain functioning (for example, having two primary DCs on the domain). I am thinking about building a second DPM server on a testing separate domain which would mirror the replicas and then restore it on testing servers from this new domain. Is it the right way to handle the data recovery testing? How did you do on your domain when you first deployed DPM? I'd be grateful for any link/documentation or advice. Thank you in advance for your help! EDIT: Two options seem possible so far: i. Create another DC/Exchange server in the alternate location; ii. Create a separate domain in the alternate location and setup a trust between this domain and the production one. The option i is certainly the best but implies setting up a secondary Exchange server, with a dedicated public IP address so that if Exchange #1 dies, we can still send emails with Exchange #2. I don't know how complex this can be and would need to discuss it with my colleagues. The option ii would only fit the testing purposes. My only question regarding this is: if my production and DPM servers are part of domain A, and there is a trust between domains A and B, can I restore a domain A content to any domain B server?

    Read the article

  • Writing a Makefile.am to invoke googletest unit tests

    - by jmglov
    I am trying to add my first unit test to an existing Open Source project. Specifically, I added a new class, called audio_manager: src/audio/audio_manager.h src/audio/audio_manager.cc I created a src/test directory structure that mirrors the structure of the implementation files, and wrote my googletest unit tests: src/test/audio/audio_manager.cc Now, I am trying to set up my Makefile.am to compile and run the unit test: src/test/audio/Makefile.am I copied Makefile.am from: src/audio/Makefile.am Does anyone have a simple recipe for me, or is it to the cryptic automake documentation for me? :)

    Read the article

  • Cross compiling unit tests with CppUnit or similar

    - by Mark
    Has anyone used a package like CppUnit to cross-compile C++ unit tests to run on an embedded platform? I'm using G++ on a Linux box to compile executables that must be run on a LynxOS board. I can't seem to get any of the common unit test packages to configure and build something that will create unit tests. I see a lot of unit test packages, CppUnit, UnitTest++, GTest, CppUTest, etc., but very little about using these packages in a cross-compiler scenario. The ones with a "configure" script imply that this is possible, but I can't seem to get them to configure and build.

    Read the article

  • SQLite assembly not copied to output folder for unit testing

    - by Groo
    Problem: SQLite assembly referenced in my DAL assembly does not get copied to the output folder when doing unit tests (Copy local is set to true). I am working on a .Net 3.5 app in VS2008, with NHibernate & SQLite in my DAL. Data access is exposed through the IRepository interface (repository factory) to other layers, so there is no need to reference NHibernate or the System.Data.SQLite assemblies in other layers. For unit testing, there is a public factory method (also in my DAL) which creates an in-memory SQLite session and creates a new IRepository implementation. This is also done to avoid have a shared SQLite in-memory config for all assemblies which need it, and to avoid referencing those DAL internal assemblies. The problem is when I run unit tests which reside a separate project - if I don't add System.Data.SQLite as a reference to the unit test project, it doesn't get copied to the TestResults...\Out folder (although this project references my DAL project, which references System.Data.SQLite, which has its Copy local property set to true), so the tests fail while NHibernate is being configured. If I add the reference to my testing project, then it does get copied and unit tests work. What am I doing wrong?

    Read the article

  • Unit testing with JMS (ActiveMQ)

    - by larry cai
    How to do unit testing with JMS ? Is it some de-facto for this ? I googled something - Unit testing for JMS: http://activemq.apache.org/how-to-unit-test-jms-code.html - jmsTemplate: activemq.apache.org/jmstemplate-gotchas.html - mockRunner : mockrunner.sourceforge.net/ Do you have any good experience on those and suggestion for me ?

    Read the article

  • Help! Sikuli unit test can not run

    - by Janet
    Hello, I couldn't run any unit tests either in the window xp? The IDE is functional. I write the simple example unit test script in the editor, as follow: def testHelloWorld(self): print("Hello World!") but no test shows up in the unit test window. When clicking the Run button of the Unit test pane, nothing happens, and the IDE window dissappears, there is no way to get back to it other than restarting the IDE. It had stucked me for several days, that would be preciate if anyone can help me solve this problem! Thank you very much. Janet

    Read the article

  • Code Coverage and Unit Testing of Python Code

    - by bhadra
    I have already visited Preferred Python unit-testing framework. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across coverage.py. Is there any better option? An interesting option for me is to integrate cpython, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to IronPython Studio). What can be done to achieve this? I look forward to suggestions.

    Read the article

  • New NCover 3.4.2 makes all my MSTest unit tests fail

    - by Steven
    Yesterday, I decided to install the newest NCover version (3.4.2). However, when I ran it on my existing .ncover configuration file, the NCover output suddenly reported that all my MSTest tests failed. Of course those tests succeed when ran within Visual Studio. Because of this, NCover isn't able to determine any coverage. Somehow the old configuration doesn't seem to work with the new version. Does anyone have any idea what the problem could be or how to solve it? Btw. Here is my ncover configuration. Project settings: Path to application to profile: c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe Arguments for the application to profile: /testcontainer:D:\dev\MyApp\MyApp.Services.Tests.Unit\bin\Debug\MyApp.Services.Tests.Unit.dll /testcontainer:D:\dev\MyApp\MyApp.WS.Tests.Unit\bin\Debug\MyApp.WS.Tests.Unit.dll Working folder: D:\dev\MyApp

    Read the article

  • Boost Unit testing memory reuse causing tests that should fail to pass

    - by Knyphe
    We have started using the boost unit testing library for a large existing code base, and I have run into some trouble with unit tests incorrectly passing, seemingly due to the reuse of memory on the stack. Here is my situation: BOOST_AUTO_TEST_CASE(test_select_base_instantiation_default) { SelectBase selectBase(); BOOST_CHECK_EQUAL( selectBase.getSelectType(), false); BOOST_CHECK_EQUAL( selectBase.getTypeName(_T("")); BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1); BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1); } BOOST_AUTO_TEST_CASE(test_select_base_instantiation_default) { SelectBase selectBase(true, _T("abc")); BOOST_CHECK_EQUAL( selectBase.getSelectType(), false); BOOST_CHECK_EQUAL( selectBase.getTypeName(_T("abc")); BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1); BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1); } The first test passed correctly, initializing all the variables. The constructor in the second unit test did not correctly set EntityType or DataPosition, but the unit test passed. I was able to get it to fail by placing some variables on the stack in the second test, like so: BOOST_AUTO_TEST_CASE(test_select_base_instantiation_default) { int a, b; SelectBase selectBase(true, _T("abc")); BOOST_CHECK_EQUAL( selectBase.getSelectType(), false); BOOST_CHECK_EQUAL( selectBase.getTypeName(_T("abc")); BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1); BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1); } If there is only one int, only the dataPos CHECK_EQUAL fails, but if there are two, both EntityType and DataPos fail, so it seems pretty clear that this is an issue with the variables being created on the same stack memory or some such. Is there a good way to clear the memory between each unit test, or am I potentially using the library incorrectly or writing bad tests? Any help would be appreciated.

    Read the article

  • Silverlight Unit Testing Framework running tests in external class library

    - by Jonas Follesø
    I'm currently looking into different options for unit testing Silverlight applications. One of the frameworks available is the Silverlight Unit Test Framework from Microsoft (developed primary by Jeff Wilcox, http://www.jeff.wilcox.name/2010/05/sl3-utf-bits/). One of the scenarios I'm looking into is running the same tests on both Silverlight 3 (PC) and Windows Phone 7. The Silverlight Unit Test Framework (SLUT) runs on both PC and phone. To prevent having to copy or link files I would like to put my tests into a shared test library, that can be loaded by either a WP7 application using the SLUT, or a Silverlight 3 application using SLUT. So my question is: will SLUT load unit tests defined in a referenced class library, or only in the executing assembly?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >