i am working with bots and the Microsoft Bot Framework.
I used the DispatchBot template to generate my bot. (https://learn.microsoft.com/de-de/azure/bot-service/bot-builder-tutorial-dispatch?view=azure-bot-service-4.0&tabs=cs)
For conversational testing, i want to create unit tests. Therefore i used this documentation to gather some informations (https://learn.microsoft.com/de-de/azure/bot-service/unit-test-bots?view=azure-bot-service-4.0&tabs=csharp)
The thing is that i dont want to test dialogs, but a single statement (a question and the right answer)
How can i implement this?
Here you can see the Start of my Dispatchbot.cs file where the magic happens (search of the correct Knowledge Base etc.)
Here's a link to how we create tests for CoreBot. The part you're most likely interested in is testing things under the /Bots directory. Based off of the test code you can find there, you likely want something like:
using System;
using System.Threading;
using System.Threading.Tasks;
using CoreBot.Tests.Common;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Adapters;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.BotBuilderSamples.Bots;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
namespace KJCBOT_Tests
{
public class BotTests
{
[Fact]
public async Task TestResponseToQuesion()
{
// Note: this test requires that SaveChangesAsync is made virtual in order to be able to create a mock.
var memoryStorage = new MemoryStorage();
var mockConversationState = new Mock<ConversationState>(memoryStorage)
{
CallBase = true,
};
var mockUserState = new Mock<UserState>(memoryStorage)
{
CallBase = true,
};
// You need to mock a dialog because most bots require a Dialog to instantiate it.
// If yours doesn't you can likely skip this
var mockRootDialog = SimpleMockFactory.CreateMockDialog<Dialog>(null, "mockRootDialog");
var mockLogger = new Mock<ILogger<DispatchBot<Dialog>>>();
// Act
var sut = new DispatchBot<Dialog>(mockConversationState.Object, mockUserState.Object, mockRootDialog.Object, mockLogger.Object);
var testAdapter = new TestAdapter();
var testFlow = new TestFlow(testAdapter, sut);
await testFlow
.Send("<Whatever you want to send>")
.AssertReply("<Whatever you expect the reply to be")
.StartTestAsync();
}
}
}
Related
I have to unfortunately write Unit Tests for a legacy Sitecore MVC code base where two distinct Sitecore Contexts are called. I understand this comes under Integration Testing but i don't have the option of educating my project Leads on that front. So i have chosen to use FakeDb for emulating Sitecore Instance and NSubstitute for substituting injected Dependencies (can't use any Profilier API Frameworks like MS Fakes, TypeMock etc because of Budget constraints). I am providing the code below:
Method to be UnitTested
public bool DubiousMethod()
{
// This HttpContext call is pain area 1. This gets resolved when i call it using ItemContextSwitcher in Unit Tests.
string currentUrl = HttpContext.Current.Request.RawUrl;
// This Sitecore Context call to Site Name is pain area 2. This gets resolved when Unit Tests are run under SiteContextSwitcher.
string siteName = Sitecore.Context.Site.Name;
return true/False;
}
Unit Test Method
[Fact]
public void DubiousMethodUT()
{
// create a fake site context
var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(
new Sitecore.Collections.StringDictionary
{
{ "name", "website" }, { "database", "web" }, { "rootPath", "/sitecore/content/home" },
{ "contentStartItem", "home"}, {"hostName","https://www.myorignalsiteurl.com"}
});
using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
{
//DubiousClassObject.DubiousMethod(home) // When Debugging after uncommenting this line i get correct value in **Sitecore.Context.Site.Name**
using (Sitecore.FakeDb.Db db = new Sitecore.FakeDb.Db
{
new Sitecore.FakeDb.DbItem("home") { { "Title", "Welcome!" } ,
new Sitecore.FakeDb.DbItem("blogs") }
})
{
Sitecore.Data.Items.Item home = db.GetItem("/sitecore/content/home");
//bool abc = confBlogUT.IsBlogItem(home);
using (new ContextItemSwitcher(home))
{
string siteName = Sitecore.Context.Site.Name;
var urlOptions = new Sitecore.Links.UrlOptions();
urlOptions.AlwaysIncludeServerUrl = true;
var pageUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item, urlOptions);
HttpContext.Current = new HttpContext(new HttpRequest("", pageUrl.Substring(3), ""), new HttpResponse(new StringWriter()));
Assert.False(DubiousClassObject.DubiousMethod(home); //When Debugging after commenting above DubiousMethodCall i get correct value for **HttpContext.Current.Request.RawUrl**
}
}
}
}
As you can observe that when i try to call the method from FakSiteContext then i am getting the correct value for Sitecore.Context.Site.Name however my code breaks when HttpContext.Current.Request.RawUrl is invoked in the method. Opposite happens when i invoke the method from ContextItemSwitcher(FakeItem) context. So far i have not been able to find a way to merge both the Contexts (which i believe is impossible in Sitecore). Can anyone suggest if i run my Unit Tests in an overarching context where i am able to contrl fakeSite Variables as well as FakeItem context variables as well and by extensions any other Sitecore Context calls?
Any help would be appreciated.
I'd recommend to take a look at Unit testing in Sitecore article as it seem to be what you need.
In short - you'll need to do a few adjustments in your code to make it testable:
1) Replace static HttpContext with abstract HttpContextBase (impl. HttpContextWrapper) so that everything can be arranged - DubiousMethod gets an overload that accepts DubiousMethod(HttpContextBase httpContext).
2) As for Sitecore Context data - it has Sitecore.Caching.ItemsContext-bound semantics (as mentioned in the article), so you could cleanup the collection before/after each test to get a sort of isolation between tests.
Alternatively you could bake a similar wrapper for Sitecore.Context as ASP.NET team had done for HttpContext -> HttpContextBase & impl HttpContextWrapper.
So here is my problem, I have an OData Web Api service that uses ODataQueryOptions to filter data from our sql server and I am trying to setup a .Net Framework Unit Test project to test the controllers with different query options. I have been searching for several days now and found many examples but most of them use an older version of OData. This example is the best one I have found so far, the only problem is that calling config.EnableDependencyInjection(); gives me the following exception:
Method not found: 'System.IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'.
Here is an example of my code:
using System.Collections.Generic;
using System.Web.Http.Results;
using System.Web.OData;
using System.Web.OData.Query;
using System.Net.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using University.API.OData.Controllers;
using University.API.OData.Models;
using System.Web.OData.Routing;
using System.Web.Http;
using System.Web.OData.Extensions;
[TestClass]
public class SalesforceUnitTest
{
private HttpRequestMessage request;
private ODataQueryOptions<Product> _options;
[TestInitialize]
public void TestInitialize()
{
request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/odata/product?$top=5");
var model = WebApiConfig.GetModel();
HttpConfiguration config = new HttpConfiguration();
config.EnableDependencyInjection(); //Throws Missing Method Exception
WebApiConfig.Register(config);
config.EnsureInitialized();
request.SetConfiguration(config);
ODataQueryContext context = new ODataQueryContext(
model,
typeof(Product),
new ODataPath(
new Microsoft.OData.UriParser.EntitySetSegment(
model.EntityContainer.FindEntitySet("product"))
)
);
_options = new ODataQueryOptions<Product>(context, request);
}
[TestMethod]
public void ProductTest()
{
var controller = new ProductController();
controller.Request = request;
var response = controller.Get(_options);
var contentResult = response as OkNegotiatedContentResult<List<Product>>;
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
}
}
Let me know if there is any other information you may need.
Thank you for any help you can provide.
EDIT:
Here what is referenced in the unit test project:
EntityFramework
EntityFramework.SqlServer
Microsoft.Data.Edm
Microsoft.Data.OData
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.DependencyInjection.Abstractions
Microsoft.OData.Core
Microsoft.Odata.Edb
Microsoft.Spatial
Microsoft.Threading.Tasks
Microsoft.Threading.Tasks.Extensions
Microsoft.Threading.Tasks.Extensions.Desktop
Microsoft.VisualStudio.TestPlatform.TestFramework
Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions
System
System.ComponentModel.DataAnnotations
System.Net
System.Net.Http
System.Net.Http.Extensions
System.Net.Http.Primitives
System.Net.Http.WebRequest.
System.Spatial
System.Web
System.Web.Http
System.Web.OData
ODataAPI
I figured it out after some more digging. It seems that my Unit Test project was using a different version than my ODataApi project. This for some weird reason was causing the MissingMethodException instead of a VersionMismatchException. Hopefully this helps someone else who is looking into why Dependency Injection isnt working for your Unit Test project.
I'm fairly new to using Moq and Nunit for unit testing and I'm having issues with one scenario. What I want is for my mock to have an out parameters which my system under test will then use to decide what action to take.
My system under test is an MVC API controller and in particular I'm trying to test the POST method. I want to return an error message for the object when validation fails.
Here is the method code for the controller:
public IHttpActionResult Post(Candidate candidate)
{
try
{
if(candidate==null)
return BadRequest();
IEnumerable<string> errors;
_candidateManager.InsertCandidate(candidate, out errors);
if (errors!=null && errors.Any())
return BadRequest(CreateErrorMessage("Invalid candidate: ", errors));
return CreatedAtRoute("DefaultApi", new {id = candidate.CandidateId}, candidate);
}
catch (Exception)
{
return InternalServerError();
}
}
This is my Unit Test Code:
[Test]
[Category("CandidateManagerController Unit Tests")]
public void Should_Return_Bad_Request_When_Creating_Invalid_Candidate()
{
IEnumerable<string> errors = new List<string>() {"error1", "error2"};
var mockManager = new Mock<ICandidateManager>();
mockManager.Setup(x => x.InsertCandidate(new Candidate(), out errors)).Callback(()=>GetErrors(errors));
var sut = new CandidateManagerController(mockManager.Object);
var actionResult = sut.Post(new Candidate());
Assert.IsInstanceOf<BadRequestResult>(actionResult);
}
What I expect is that when _candidateManager.InsertCandidate() is run then the errors variable is populated. However what is happening is that when you step through the controller code errors is null after _candidateManager.InsertCandidate() method is run.
If anyone has any ideas what I'm doing wrong or if what I want to do is not possible using Moq then please let me know.
Thanks
What you want to do is possible. If you look at the Quickstart docs at https://github.com/Moq/moq4/wiki/Quickstart, there is a section where it shows how you do setups for methods using out params. I have made two corrections to your code and it works.
You have to use the same candidate instance for both the mock setup and when you exercise the sut. Otherwise, Moq thinks that the two objects are different and your test setup becomes useless.
You don't have to use Callback in order to set the errors returned by the mocked CandidateManager.
Below is your test method with my changes.
[Test]
[Category("CandidateManagerController Unit Tests")]
public void Should_Return_Bad_Request_When_Creating_Invalid_Candidate()
{
IEnumerable<string> errors = new List<string>() {"error1", "error2"};
//instance to be used for both setup and test later
var candidate = new Candidate();
var mockManager = new Mock<ICandidateManager>();
//removed Callback
mockManager.Setup(x => x.InsertCandidate(candidate, out errors));
var sut = new CandidateManagerController(mockManager.Object);
var actionResult = sut.Post(candidate);
Assert.IsInstanceOf<BadRequestResult>(actionResult);
}
You have to make sure that when you call your SUT that you use the same instance passed to the out argument otherwise the call will fail.
In your example, the method under test passes a null instance into the mocked method thus negating the setup of the test.
If however you are not able to supply the same instances for the out then it doesn't look like you will be able to get a mock to pass successfully. Take a look a the Quick Start for Moq to get an understanding of it capabilities.
If you customize an autoroute part you have the option to recreate the url on each save.
The help text under this option says:
"Automatically regenerate when editing content
This option will cause the Url to automatically be regenerated when you edit existing content and publish it again, otherwise it will always keep the old route, or you have to perform bulk update in the Autoroute admin."
I have digged all around but I cannot find anywhere an "Autoroute admin".
Is it really there?
It was a proposed feature never implemented?
Any idea to do a bulk update even without an Admin page?
Thanks
EDIT after #joshb suggestion...
I have tried to implement a bulk operation in my controller.
var MyContents = _contentManager.Query<MyContentPart, MyContentPartRecord>().List().ToList();
foreach (var MyContent in MyContents) {
var autoroutePart = recipe.ContentItem.As<AutoroutePart>();
autoroutePart.UseCustomPattern = false;
autoroutePart.DisplayAlias = _autorouteService.GenerateAlias(autoroutePart);
_contentManager.Publish(autoroutePart.ContentItem);
}
In this way it recreates all aliases for the types that contain the given part MyContentPart.
With some more work this code can be encapsulated in a command or in a new tab in Alias UI.
After finished the current project I'm doing I will try that...
You could create a module and implement a command that does a bulk update. Shouldn't be too much work if you're comfortable creating modules. You'll need to implement DefaultOrchardCommandHandler and inject IContentManager to get all the parts you're interested in.
Enable Alias UI in the modules section will give you the admin section for managing routes, however I'm not sure what kind of bulk updates it offers
Publishing the ContentItem will do nothing if it is already Published (as it was in my case).
Instead, one could call the PublishAlias method on the AutorouteService. I ended up with a Controller, something like this:
using Orchard;
using Orchard.Autoroute.Models;
using Orchard.Autoroute.Services;
using Orchard.ContentManagement;
using Orchard.Localization;
using Orchard.Security;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace MyNamespace.MyModule.Controllers {
public class AutorouteBulkUpdateController : Controller {
private readonly IOrchardServices _orchardServices;
private readonly IAutorouteService _autorouteService;
private Localizer T { get; set; }
public AutorouteBulkUpdateController(IOrchardServices orchardServices, IAutorouteService autorouteService) {
_orchardServices = orchardServices;
_autorouteService = autorouteService;
T = NullLocalizer.Instance;
}
public ActionResult Index() {
if (!_orchardServices.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage settings"))) {
return new HttpUnauthorizedResult();
}
int count = 0;
IEnumerable<AutoroutePart> contents;
do {
//contents = _orchardServices.ContentManager.Query<AutoroutePart>(VersionOptions.Latest, new string[] { "Page" }).Slice(count * 100, 100).ToList();
contents = _orchardServices.ContentManager.Query<AutoroutePart>(VersionOptions.Latest).Slice(count * 100, 100).ToList();
foreach (var autoroutePart in contents) {
var alias = _autorouteService.GenerateAlias(autoroutePart);
if (autoroutePart.DisplayAlias != alias) {
autoroutePart.UseCustomPattern = false;
autoroutePart.DisplayAlias = alias;
_autorouteService.PublishAlias(autoroutePart);
}
}
_orchardServices.TransactionManager.RequireNew();
_orchardServices.ContentManager.Clear();
count += 1;
} while (contents.Any());
return null;
}
}
}
I'm just getting my feet wet in Nancy. I was really excited to see the Testing process in the Wiki, but when I tried the following I couldn't get it work pass the tests at first.
Using VS2010
Created Empty ASP.NET Web Application Project: Notify.App
Install-Package Nancy.Hosting.AspNet
Created simple Module as listed below: NotifyModule
Created Class Library Project: Notify.UnitTests
Install-Package Nancy.Testing
Install-Package XUnit
Created simple first test: BaseUrlSpec.cs
Using DefaultNancyBootstrapper the test fails with HttpStatusCode.NotFound.
If I replace the bootstrapper definition with:
var bootstrapper = new ConfigurableBootstrapper(
with =>
with.Module<NotifyModule>());
then the test passes. I don't understand why the SDHP using the DefaultNancyBootstrapper didn't work? Did I do something wrong to make it break, or am I missing details in my understanding?
NotifyModule
using Nancy;
public class NotifyModule : NancyModule {
public NotifyModule() {
Get["/"] = _ => HttpStatusCode.OK;
}
}
BaseUrlSpec
using Nancy;
using Nancy.Testing;
using Notify.App;
using Xunit;
public class BaseUrlSpec
{
[Fact]
public void ShouldRespondOk()
{
var bootstrapper = new DefaultNancyBoostrapper();
var app = new Browser(bootstrapper);
var response = app.Get("/", with => with.HttpRequest());
var statusCode = response.StatusCode;
Assert.Equal(HttpStatusCode.OK, statusCode);
}
}
You need to make sure the assembly containing your route is loaded. Referencing a type from your assembly ensures this, therefore the version using the configurable bootstrapper works.
To make the other one work, just add a reference to some type from your assembly. No need to instantiate it.