I am trying to integrate NUnit in my windows phone project to test asynchronous web service calls. I am referring to NUnitTestRunnerWP7 dll. Here is what I did.
But the asynchronous callback method is called after the Assert statement, hence it does not work. How can I execute the Assert after my callback? If I write the failed Assertion in callback, my application crashes.
[Test]
public void TestAsyncFunc(){
string result;
ManualResetEvent manualReset = new ManualResetEvent(false);
MyWebServiceClient client = GetMyWebServiceClient(); //added a service reference for asmx services
client.LoginCompleted += delegate(object sender, EventArgs args)
{
result = args.Result.ToString();
manualReset.Set();
};
client.LoginAsync("username", "password");
if (!manualReset.WaitOne(5000))
Assert.Fail();
Assert.AreEqual("", result);
}
I don't understand what am I missing. Any help would be appreciated.
Thanks in advance.
Related
I have a background task initiated in .net core 2.0 startup, inherits from backgroundservice, implementing StartAsync, StopAsync and ExecuteAsync. This task is to update some data in database table periodically based on some business logic.
While I can run the backgroundtask as an application and test using logs, db check and with the help of other tools, can the unit-testing is necessary for testing the backgroundtask? If so how to register the task as a service with dependencies and trigger the start and stop methods to assert the actual vs expected? Appreciate some basic sample unit-test method on testing timer based .net core ihostedservice backgroundtask.
Here is my basic test start just for sample, but not completed yet. Having said that, this is just a thought but not the exact working test. Here is what need some help from the community. Can also add some more asserts i.e. Assert.Verify()?
[Fact]
public async void Run_background_task_success()
{
//Arrange
IServiceCollection services = new ServiceCollection();
services.AddHostedService<BackgroundManagerTask>();
var serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetService<IHostedService>() as BackgroundManagerTask;
var isExecuted = false;
if(await service.StartAsync(CancellationToken.None))
{
isExecuted = true;
}
await Task.Delay(10000);
Assert.True(isExecuted);
await service.StopAsync(CancellationToken.None);
}
Here's how I usually do it. You mention you are going to the database to update some data, so I'm assuming you are expecting that as a dependency from BackgroundManager
[Fact]
public void BackgroundManagerUpdatingDataTest()
{
// Arrange
Mock<IDataAccess> dbMock = new Mock<IDataAccess>();
dbMock.Setup(x => x.UpdateSomethingInDB(It.IsAny<BusinessObject>())).Returns(1); // One row updated from the DML in UpdateSomethingInDB from the BusinessObject
BackgroundManager sut = new BackgroundManager(dbMock.Object); // System under test.
// Act
await sut.StartAsync(CancellationToken.None);
await Task.Delay(500); // Give the test some time to execute.
await sut.StopAsync(CancellationToken.None); // Stop the Background Service.
// Assert
dbMock.Verify(x => x.UpdateSomethingInDB(It.IsAny<BusinessObject>()), Times.Exactly(1));
}
Above, we are plainly testing the update to the database occurred by Mocking the data access call and verifying that it was called exactly once.
You could of course Mock any other dependency out using Moq and Assert on anything else you want to verify.
I am trying to write an integration test for JMS service which looks like something like this.
#JmsListener(destination = "mailbox", containerFactory = "myFactory")
public void receiveMessage(Email message) throws InterruptedException {
try {
sendEmail(message);
}catch (Exception e){
LOGGER.log(Level.SEVERE,"Failed to deliver email",e);
Thread.sleep(TimeUnit.SECONDS.toSeconds(Optional.of(retryInterval).orElse(5)));
throw e;
}
}
private void sendEmail(Email message){
...............
}
First of all, can I mock this some how? I tried mocking it, but when I send a message the spring boot application is calling the actual JMS bean not the mock one. Seems like this is not possible.
Even if this is not possible, can I at least aoutowire the bean and somehow check if the receiveMessage method is being invoked. Furthermore, if it is being invoked, the sendEmail part should be faked so that it does not do any work. I have a few ideas such as creating a subclass for testing, but not happy with either of them. So wanted to if you can suggest me a better work around?
One approach is to use different profiles for say development, integration test and production and annotate the different components and your integration test class accordingly.
#Component
#Profile("it")
public class MessageReceiverIT {
#JmsListener(destination = "mailbox", containerFactory = "myFactory")
public void receiveMessage(SimpleMessage email) {
log.info("Integration test pretend to receive {}", email);
// (...)
This is the Integration test that uses the same Application class as the real Application, but if a message is received the MessageReceiverIT.receiveMessage() method will be invoked instead of the production component:
#RunWith(SpringRunner.class)
#SpringBootTest(classes=Application.class)
#ActiveProfiles("it")
public class JmsIntegrationTest {
#Inject
ConfigurableApplicationContext context;
#Test
public void testSend() throws Exception{
JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
jmsTemplate.convertAndSend("mailbox", new SimpleMessage("it", "we need more IT"));
// (...)
Also check out Spring Boot Testing for alternative approaches such as the use of #TestConfiguration. I'm using Spring Boot in my examples, but there should be similar approaches if you have a none Spring Boot Application.
My unitTests not longer work after Update from Kentico 9 to Kentico 10.
I have a UnitTest like this. (worked fine on Kentico 9)
[SetUp]
public void setUp()
{
this.pageCreator = new PageCreator();
this.fixture = new Fixture();
this.fixture.Customize(new AutoMoqCustomization());
}
[Test]
public void execute()
{
this.pageCreator.Execute(null);
}
I just try to call this Function
public class PageCreator : ITask
{
public string Execute(TaskInfo task)
{
try
{
this.treeProvider = new TreeProvider(MembershipContext.AuthenticatedUser);
this.createPages(this.treeProvider);
return successMessage;
}
catch (Exception ex)
{
this.sendMailToDeveloper(ex.Message);
return "Fail";
}
The Problem is, when I try run my test, I get an Error (because of MembershipContext.AuthenticatedUser [CMS.Membership.MembershipContext.AuthenticatedUser" hat eine Ausnahme vom Typ "System.InvalidOperationException" verursacht])
When I try to make the same in debugMode, everything is working fine.
What can be the problem and how can I fix it ?
I have load all the new Dll from Kentico 10 but nothing changed.
Thanks for your help
try updating your references on the test project to use the Kentico10 nuget packages. the release notes have a section on Automated Tests - https://docs.kentico.com/k10/release-notes-kentico-10
"Automated testing – New Kentico.Libraries.Tests integration package, which separately provides all functionality related to automated testing of the Kentico API. The testing API is no longer available directly within Kentico projects or the main Kentico.Libraries integration package."
I'm writing a USB device API for Windows Store Apps that uses Windows.Devices.USB API from Windows 8.1 to connect and communicate with the custom USB device. I'm using the Visual Studio 2013 dev preview IDE.
The following function in the library is used to connect to the USB device.
(Simplified for clarity)
public static async Task<string> ConnectUSB()
{
string deviceId = string.Empty;
string result = UsbDevice.GetDeviceSelector(new Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"));
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(result, null);
if (myDevices.Count > 0)
{
deviceId = myDevices[0].Id;
}
UsbDevice usbDevice = null;
try
{
usbDevice = await UsbDevice.FromIdAsync(deviceId);
}
catch (Exception)
{
throw;
}
if (usbDevice != null)
return "Connected";
return string.Empty;
}
When called from the Windows Store App project, this function connects to the device flawlessly. However, when called from the Unit Test Library for Windows Store Apps project, the statement in the try block throws an exception.
A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
from what I've looked around, this happens when an Async function is called without the await keyword. But I'm using the await keyword alright!
Some more info, I am unable to use NUnit to write unit tests for Store Apps so am using the MSTest Framework.
[TestClass]
public class UnitTest1
{
[TestMethod]
public async Task TestMethod1()
{
await ConnectToUSB.ConnectUSB();
}
}
Also, I've included the following capability tags in the manifest files of both the App store projects too without which it's impossible for the Store Apps to connect to devices.
<m2:DeviceCapability Name="usb">
<m2:Device Id="vidpid:ZZZZ XXXX">
<m2:Function Type="name:vendorSpecific" />
</m2:Device>
</m2:DeviceCapability>
Is there something I'm missing or is this a bug in the MSTest Framework?
I think the problem is that
await UsbDevice.FromIdAsync(deviceId);
must be called on the UI thread because the app has to ask the user for access.
You have to CoreDispatcher.RunAsync to ensure you're on the UI thread or actually be in the code behind for a page.
I had the same problem with Unit Test App (Universal Windows) in VS 2017.
I verify answer of my predecessor Greg Gorman(see below). And I found this is true.
If you uses inside method body this construct:
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
...
UsbDevice usbDevice = await UsbDevice.FromIdAsync(deviceId);
...
}).AsTask().Wait();
the FromIDAsync will work as you expect.
For your example change the test method to this:
[TestClass]
public class UnitTest1
{
[TestMethod]
public async Task TestMethod1()
{
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
await ConnectToUSB.ConnectUSB();
}).AsTask().Wait();
}
}
i have a j2me application with web service stub.
it worked in some mobiles.
but in some mobiles "Application Error" comes up.
i tried creating package making versions MIDP 2.0 and CLDC 1.0(made stub for CLDC 1.0 also)
still it is showing "Application Error"
if I create the package without stub the application works properly.
The stub was generated using "Sun Java Wireless Toolkit 2.5.2 for CLDC"
can anyone help?
new Thread(new Runnable(){
public void run()
{
try {
MobiService_Stub ms = new MobiService_Stub();
resultBox.setString(ms.sendString( textbox.getString()));
}catch (JAXRPCException cnfe){
resultBox.setString("No connection found");
} catch (RemoteException e) {
// TODO Auto-generated catch block
resultBox.setString(e.getMessage());
}
}
}).start();
resultBox.addCommand(cmd_Cancel);
}
I have come up with "Application Error" messages when I try to run a Midlet that uses a JSR not available in that device. You should verify that the JSR or APIs you import are supported by your testing devices.