3

Using Microsoft.aspnetcore.testhost I am unable to make http get to controller action returning razor view. I need to test the response has specific security headers and have other test I would like to perform on the action responses. Razor throws compilation exceptions for every namespace it hits, not just the system example below:

oclq12bb.ugz(5,11): error CS0246: The type or namespace name 'System' could
not be found (are you missing a using directive or an assembly reference?)
oclq12bb.ugz(6,11): error CS0246: The type or namespace name 'System' could
not be found (are you missing a using directive or an assembly reference?)

Repro:

  • Using visual studio 2017 create a new asp.net core 1.1 web project and add a .net core unit test project.
  • Remove the appsettings from startup.
  • Set view /home/index.cshtml to copy to output directory to "copy always".
  • create and run unit test. Throws exception.

Code:

[TestClass]
public class UnitTest1
{
    private readonly HttpClient _client;

    public UnitTest1()
    {
        var server = new TestServer(
            new WebHostBuilder().UseStartup<Startup>());
        _client = server.CreateClient();
    }

    [TestMethod]
    public async Task Test1()
    {
        var response = await _client.GetAsync("/");
    }
}

I have tried publishing the web project to a folder and using the .UseContentRoot() in place of copy always. Same result.

1

1 Answer 1

4

The longday's comment has actually worked for me. To make this question answered and more useful to others, let me put the actual code that works. This is my code from my project but it is very generic.

using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.TestHost;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Shevastream.Models;
using Shevastream.Services.Factories;
using Xunit;

namespace Shevastream.Tests.IntegrationTests
{
    public class PagesTests
    {
        /// <summary>
        /// Server object which mimics a real running server
        /// </summary>
        private readonly TestServer _server;
        /// <summary>
        /// Client object which mimics a real client
        /// </summary>
        private readonly HttpClient _client;

        private readonly IDataContext _dataContext;

        /// <summary>
        /// Setup mock server and client
        /// </summary>
        public PagesTests()
        {
            var path = PlatformServices.Default.Application.ApplicationBasePath;
            var contentPath = Path.GetFullPath(Path.Combine(path, $@"../../../../src"));

            _server = new TestServer(
                new WebHostBuilder()
                    .UseContentRoot(contentPath)
                    .UseStartup<Startup>()
                    .ConfigureServices(services =>
                    {
                        services.AddSingleton<IHttpClientFactory, HttpClientFactory>();
                        services.Configure((RazorViewEngineOptions options) =>
                        {
                            var previous = options.CompilationCallback;
                            options.CompilationCallback = (context) =>
                            {
                                previous?.Invoke(context);

                                var assembly = typeof(Startup).GetTypeInfo().Assembly;
                                var assemblies = assembly.GetReferencedAssemblies().Select(x => MetadataReference.CreateFromFile(Assembly.Load(x).Location))
                                .ToList();
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location));
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Private.Corelib")).Location));
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor")).Location));
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("mscorlib")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Private.Corelib")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Linq")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Threading.Tasks")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location)); assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Dynamic.Runtime")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor.Runtime")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Mvc")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Razor")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Mvc.Razor")).Location));
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.AspNetCore.Html.Abstractions")).Location)); 
                                assemblies.Add(MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Text.Encodings.Web")).Location));

                                context.Compilation = context.Compilation.AddReferences(assemblies);
                            };
                        });
                    })
            );

            _client = _server.CreateClient();

            var serviceProvider = Extensions.RegisterServices().BuildServiceProvider();
            _dataContext = serviceProvider.GetRequiredService<IDataContext>();
        }

        [Theory]
        [InlineData("/home")]
        [InlineData("/home/profile")]
        [InlineData("/store/product")]
        [InlineData("/home/contact")]
        [InlineData("/store/cart")]
        [InlineData("/home/faq")]
        [InlineData("/account/login")]
        public async Task TestSimplePages(string url)
        {
            // Act
            var ok = await _client.GetAsync(url);

            // Assert
            Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.