The method below is working as intended when running through tests in MS test and through a Console application. When running it through a NUnit test I get an WebException.
Has any one else had this problem, and is there a way around it? It is not an option to use another testing framework.
public void Download(string username, string password, string dwlFileName, string dwlUrl)
{
var webClient = new WebClient();
webClient.Headers.Add("Authorization",
"Basic " +
Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + ":" + password)));
webClient.DownloadFile(dwlUrl, dwlFileName);
}
Exception:
System.Net.WebException was caught
HResult=-2146233079
Message=The remote server returned an error: (403) Forbidden.
Source=System
StackTrace:
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at TestProject.WebHelper.Download(String username, String password, String dwlFileName, String dwlUrl) in TestProject.WebHelper...
InnerException: null
Enviroment
Visual Studio 2012
NUnit 2.6.3
Any help would be much appreciated. Thanks! :)
EDIT
Have tried Nunit testrunner and resharpner test runner. Both fails.
I used wireshark to examine the the data sent. And found out there is one more call on the nunit test then the ms-test.
Until you answer the question, one thing to keep in mind is that the actual test runs under the process of the test runner. If the runner has some issues/restrictions those might interfere probably.
Do you have multiple tests that try to access that URL? In that case the server might have some security policies and will drop requests that might consider to be Denial of Service(too similar that come in too often).
Try adding a user agent header: webClient.Headers.Add("user-agent", "Other");
Related
I am using aspnetboilerplate 5.1.0.
In the ProjectName.Web.Tests I have run into a situation that I cannot solve.
I have set up web tests for my controller using [Fact] or [Theory].
When I attempt to run the tests using GetResponseAsString(string url, HttpStatusCode expectedStatusCode = HttpStatusCode.OK) found in the webtestbase class. All the tests fail.
Here is an example of my Test:
[Fact]
public async Task Index_Test()
{
//Act
var response = await GetResponseAsStringAsync(
GetUrl<HomeController>(nameof(HomeController.Index))
);
//Assert
response.ShouldNotBeNullOrEmpty();
}
The Tests all fail on this:
Message:
Shouldly.ShouldAssertException : response.StatusCode
should be
HttpStatusCode.OK
but was
HttpStatusCode.NotFound
I have other aspnetboilerplate projects in version 3.8.3 and 4.2.1 and the web tests work just fine. So I'm not sure why the server is not able to find the action methods on my controllers.
The service tests found in the ProjectName.Tests project run just fine.
I found the culprit. The problem I was experiencing was due to attempting to copy a project for web unit tests from one of the aspnetboilerplate project template repositories and updating all of the references and class names to match the names and namespaces in the destination VS solution.
I submitted a similar question on the aspnetboilerplate github account.
https://github.com/aspnetboilerplate/aspnetboilerplate/issues/5463.
Ultimately, here is what happened.
After going through the same process with a newer project. I found that In the
class file that would by default be named AbpProjectNameWebTestBase.cs in the method
protected override IWebHostBuilder CreateWebHostBuilder()
{
return base
.CreateWebHostBuilder()
.UseContentRoot(ContentRootFolder.Value)
.UseSetting(WebHostDefaults.ApplicationKey, typeof(AbpProjectNameWebModule).Assembly.FullName);
}
I mistakenly replaced AbpProjectNameWebModule with AbpProjectNameTestModule instead of AbpProjectNameWebMvcModule. This was trying to use the Application Service Unit test project as the web project. Therefore it could not find any of the referenced URI's and therefore returned httpStatusCode.NotFound.
After fixing this reference. I started getting exceptions that pertained to the public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) method.
These were things like adding app.UseAuthentication() and app.UseAuthorization() as well as needing to add a Middleware to provide a ClaimsIdentity and ClaimsPrincipal for the context.User (i.e. app.UserMiddleware<TestAuthenticationMiddleware>())
Now, I am able to get my web unit tests to run as I had in previous versions.
we are currently setting up our automatic testing for one of our CakePHP Applications. First of we are trying the Cake Core tests with a fresh CakePHP 2.7.11. (Don't worry as soon as the tests are all up and running, we will be upgrading ;-) ) Unfortunatly the CakeSocketTest::testEnableCrypto() fails everythim with the following message:
SocketException: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
I am guessing it has something to do with the Testservers setup. But I am not sure where to start my search.
If anybody has a hint what I could do it would be very appreciated.
Thanks!
[UPDATE]
public function testEnableCrypto() {
// testing on ssl server
$this->_connectSocketToSslTls();
$this->assertTrue($this->Socket->enableCrypto('sslv3', 'client'));
$this->Socket->disconnect();
// testing on tls server
$this->_connectSocketToSslTls();
$this->assertTrue($this->Socket->enableCrypto('tls', 'client'));
$this->Socket->disconnect();
}
I am writing a unit test for login process and have used simple membership api.
from web project, login is working fine, but while in unit test. simple membership api is raising exception.
API is throwing error on WebSecurity.Login method.
System.NullReferenceException was caught
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=System.Web
StackTrace:
at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie, String strCookiePath)
at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie)
at WebMatrix.WebData.WebSecurity.Login(String userName, String password, Boolean persistCookie)
at [ code ]
InnerException:
WebSecurity.UserExists is working fine.
I think, error is due to 'cookies object is not available in unit test project'
acually WebSecurity.Login uses FormsAuthentication.SetAuthCookie behind the scene,
since FormsAuthentication.SetAuthCookie uses old httpcontext api therefore even with moq httpcontext it is throwing exception.
http://forums.asp.net/t/1871234.aspx
so solution is to dependency injection.
FormsAuthentication.SetAuthCookie mocking using Moq
http://forums.asp.net/post/5257516.aspx
I have a small problem, I have created some Selenium tests. The problem is I can't order the testcases I have created. I know unit testing should not be ordered but this is what I need in my situation. I have to follow these steps: login first, create a new customer, change some details about the customer and finally log out.
Since there is no option to order unit tests in NUnit I can't execute this.
I already tried another option, to create a unittest project in Visual Studio, because Visual Studio 2012 has the ability to create a ordered unit test. But this is not working because I can't run a unit test while I am running my ASP.NET project. Another solution file is also not a good option because I want to verify my data after it has been submitted by a Selenium test.
Does someone of you have another solution to solve my problem?
If you want to test all of those steps in a specific order (and by the sounds of it, as a single session) then really it's more like an acceptance test you are talking about; and in that case it's not a sin to write more complex test methods and Assert your conditions after each step.
If you want to test each step in true isolation (a pure unit test) then each unit test must be capable of running by itself without any reference to any other tests; but when you're testing the actual site UI itself this isn't really an option for you.
Of course if you really you want to have every single test somehow setup every single dependency without reference to any other actions (e.g in the last test you would need to fake the login token, your data layer will have to pretend that you added a new customer, etc. A lot of work for dubious benefit...)
I say this based on the assumption that you already have unit tests written for the server-side controllers, layers, models, etc, that you run without any reference to the actual site running in a browser and are therefore confident that the various back-end part of your site do what they are supposed to do
In your case I'd recommend more of a hybrid integration/acceptance test
void Login(IWebDriver driver)
{
//use driver to open browser, navigate to login page, type user/password into box and press enter
}
void CreateNewCustomer(IWebDriver driver)
{
Login(driver);
//and then use driver to click "Create Customer" link, etc, etc
}
void EditNewlyCreatedCustomer(IWebDriver driver)
{
Login(driver);
CreateNewCustomer(driver);
//do your selenium stuff..
}
and then your test methods:
[Test]
void Login_DoesWhatIExpect()
{
var driver = new InternetExplorerDriver("your Login URL here");
Login(driver);
Assert(Something);
}
[Test]
void CreateNewCustomer_WorksProperly()
{
var driver = new InternetExplorerDriver("your Login URL here");
CreateNewCustomer(driver);
Assert(Something);
}
[Test]
void EditNewlyCreatedCustomer_DoesntExplodeTheServer()
{
var driver = new InternetExplorerDriver("your Login URL here");
EditNewlyCreatedCustomer(driver);
Assert(Something);
}
In this way the order of the specific tests do not matter; certainly if the Login test fails then the CreateNewCustomer and EditNewlyCreatedCustomer tests will also fail but that's actually irrelevant in this case as you are testing an entire "thread" of operation
UPDATE: SO I am getting the error whenever I have all meta tags like HostType,AspNetDevelopmentServerHost,URLToTest. So when I comment these tags I can run the test but I need to have these tags to have the connection string available for controller to connect to database.
I created a basic unit test by just right clicking on the action in asp.net mvc and saying Create unit tests...I am just trying to run a basic unit test.I am getting this error -
The test adapter 'WebHostAdapter' threw an exception while running test 'IndexTest'. The web site could not be configured correctly; getting ASP.NET process information failed. Requesting 'http://localhost:55767/VSEnterpriseHelper.axd' returned an error: The remote server returned an error: (500) Internal Server Error.
This is my method -
[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("C:\\Users\\Administrator\\Desktop\\MyWebsite\\Websites\\Customer1\\Customer1", "/")]
[UrlToTest("http://localhost:55767/Admin/Dashboard")]
public void IndexTest()
{
DashboardController target = new DashboardController(); // TODO: Initialize to an appropriate value
string id = string.Empty; // TODO: Initialize to an appropriate value
ActionResult expected = null; // TODO: Initialize to an appropriate value
ActionResult actual;
actual = target.Index(id);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
Any ideas what would be the problem here ? I tried to google but didnt get a good solution for my problem. I am using VS2010 Ultimate and asp.net mvc 2.0.
I created a basic unit test by just right clicking on the action in asp.net mvc and saying Create unit tests..
When you do this on an ASP.NET web application project (which is what MVC uses) Visual Studio will generate a ton of crap and will try to start the web server every time you want to run a single unit test. You don't want this.
Here are two possibilities:
When you start a new ASP.NET MVC project select that you want a unit test project in the default template (preferred).
You already have an ASP.NET MVC project and you want to add unit tests to it. In this case simply right click on the solution and add a new project of type Test Project. Now add reference to the ASP.NET MVC project you are testing and add a new unit test (Add New Item).