How to test GWT/GWTP project? - unit-testing

I am currently building a web application using GWT, GWTP.
And I have some questions about testings:
Is there a Lint-like tool for GWTP or GWT?
How to test presenters? (GWTP with Mockito)
How to test views?
Thanks.

Presenters can be easily unit-tested using Jukito. Here's a quick example of a Presenter being tested using Jukito.
#RunWith(JukitoRunner.class)
public class ShowCommentsPresenterTest {
#Inject
private ShowCommentsPresenter showCommentsPresenter;
#Inject
private PlaceManager placeManager;
#Test
public void onReset_PlaceRequestHasNoShowId_ShouldHideView() {
//given
when(placeManager.getCurrentPlaceRequest()).thenReturn(new PlaceRequest());
//when
showCommentsPresenter.onReset();
//then
verify(showCommentsPresenter.getView()).hide();
}
#Test
public void onReset_PlaceRequestHasAShowId_ShouldDisplayView() {
//given
String someShowId = "12345";
when(placeManager.getCurrentPlaceRequest()).thenReturn(new PlaceRequest()
.with(ParameterTokens.getShowId(), someShowId));
//when
showCommentsPresenter.onReset();
//then
verify(showCommentsPresenter.getView()).display();
}
}
In GWTP's philosophy, Views should not be unit-tested directly. Using a dumb View that is a slave to the Presenter, most of the logic can be tested through unit tests on the Presenters. Tools like Selenium are a better fit for testing UI interactivity.

Google put out a great article about using different testing methodologies with GWT. Definitely check it out. Personally, I use JUnit when I'm testing back-end stuff like business logic, and Selenium for testing the UI and application as a whole from the browser's perspective.

Related

Testing NUnit Startup Azure Function

I want to put Unit Test to this class with NUnit, how do I do it?
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Universal.DataTransferNCFDGII.Function.Services;
[assembly: FunctionsStartup(typeof(Universal.DataTransferNCFDGII.Function.Startup))]
namespace Universal.DataTransferNCFDGII.Function
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddSingleton<IInsertData, InsertData>();
}
}
}
Generally you do not test classes and methods Startup and Configure as there is no real logic of yours in need of testing. You would just be testing that the dependency injection setup works and that is not your code. It is a good practice while writing tests to remember to only test your code, not third party or .NET libraries. It would be better to cover this with an integration test, rather than unit test.
If you are concerned with no test for this class and method impacting your code coverage, you can just put the ExcludeFromCodeCoverage attribute on your method or class, like this:
[ExcludeFromCodeCoverage]
public override void Configure(IFunctionsHostBuilder builder)

To develop a testing tool

Now, I am trying to develop a testing tool, which can make unit testing. I mean I want to use JUnit in my testing tool to test other projects. But I don't know how to insert JUnit into my testing tool. Is it possible to do that and how? And is there any other open-source testing tool can be inserted into my testing tool?
To use Junit API make sure you got the jar in the classpath
To use Junit tests you need the testing class to extend SystemTestCase4
and your function to have #Test annotation above it
if you want code to run before your test so use function with #Before
and if you want after use function with #After
public class BaseTest extends SystemTestCase4 {
#Before
public void beforeEachTest() throws Exception {
}
#Test
#TestProperties(name = "test test ")
public void testTest() throws Exception {
//run your tested code
}
#After
public void afterEachTest() throws Exception {
}
as for how to test your projects it depend what tests you want to do?
For unit testing just add your own tests inside the projects
Integration, Functional or other tests need you to understand how to "Attack" it, meaning if it's UI tests for web so use tools for that (Selenium for example) if it's for checking network so use JMeter

Best API / lib to unit test Jersey Restful Web Services?

What is the best library / API to unit test Jersey based Restful Web Services? Some APIs like JerseyTest seem outdated (had conflicts when using them in my pom) and also seem to be depending on a particular container, such as Glassfish or Grizzly... I am deploying my Jersey based Restful Web Services as a war file into Tomcat 7. Is there a way to use a testing framework which has an embedded web server or in-memory solution? Thanks again.
There are couple of frameworks that I am aware of atleast :
REST-EASY : http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/
Jersey Test Framework : https://jersey.java.net/documentation/1.17/test-framework.html
Jersey test Framework is easier to use.
I'm using rest-assured for many of my projects as it offers a highly specialized dsl to write your tests and once you've grown custom to the notation, writing tests is done really quick.
A variety of examples can be found on the project website but for a quick preview - a sample test could look like this snippet:
expect()
.statusCode(200)
.body("user.id", equalTo(1))
.when()
.given()
.contentType(ContentType.JSON)
.get("http://test/rest");
As my blog was quoted by Balaji, I'd like to add that there is this article of mine with more examples for the rest-assured framework and also a downloadable REST-server for testing the examples.
A test example with jersey-test could look like this example taken from the project's documentation:
public class SimpleTest extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void test() {
final String hello = target("hello").request().get(String.class);
assertEquals("Hello World!", hello);
}
}

Testing web services with JUnit

I'm developing an application to perform a series of tests on various web services. These web services consume and produce json, and for each of them we have a class to model the json request and response. For example:
If the json request for serviceX is something like this:
{
"name":"Alex",
"id":"123"
}
We have a class serviceXrequest like this:
public class serviceXrequest {
String name;
String id;
//Constructor, getters/setters, etc
...
}
With an object of that class as the starting point, we can perform a series of test on the web service. The idea is to make those test as generic as possible so they can be used with any web service by just writing a class that models it's request and a class to model the response.
For that reason, all of the test methods developed so far work with plain java objects. This is an example of what I want to have:
public class WebServiceTest {
String serviceURL;
String requestJson;
String requestClass;
String responseClass;
public WebServiceTest() {}
#Test
public static void Test1() { ... }
#Test
public static void Test2() { ... }
....
#Test
public static void TestN() { ... }
}
And then, from another class, invoke those tests with doing something like this:
public class LoginTest { //To test the login web service, for example
public static void main(String[] args) {
WebServiceTest loginTest = New WebServiceTest();
loginTest.setServiceURL("172.0.0.1/services/login");
loginTest.setRequestJson("{"user":"ale","pass":"1234"}");
...
loginTest.runTests();
}
}
I know it's not that simple, but any ideas on how to get there?
Thanks in advance!!
You might also look into REST-assured
One of the best tools for testing your webservices is SOAP UI, but this is more for functional testing
As well I integrated very well FitNesse tests
JMeter goes hand in hand with LoadUI ..kind of same things in terms of stress and load tests for webservices.
Junit...i never used directly applied to the webservice itself.
Most of the times I had a Spring service called by the implemetation of the WebService interface (Port) and I unit tested that one.
You should consider using http-matchers (https://github.com/valid4j/http-matchers) which let's you write JUnit-tests, using regular hamcrest-matchers (bundled with JUnit) to test your web-service via standard JAX-RS interface.

Can I unit test a method that makes Sitecore context calls?

I'm working on a web application that is built over Sitecore CMS. I was wondering if we could unit test for example a method that takes some data from Sitecore makes some processing with it and spits out a result. I would like to test all the logic within the method via a unit test.
I pretty confused after searching the internet wide and deep. Some say that this kind of testing is actually integration testing and not unit testing and I should test only the code that has no Sitecore calls, others say that this is not possible because the Sitecore context would be missing.
I would like to ask for your help experienced fellow programmers:
Can I unit test a method that contains Sitecore calls ? If YES, how ? If NO, why ? Is there any workaround ?
The project is at its beginning, so there will be no problem in choosing between unit testing frameworks such as MSTest or Nunit, if it is the case that the solution is related to the unit testing framework of choice.
It's pretty hard to find out anything about Sitecore without providing email and living through the sales pitch, so I'll just provide a generic approach on how to do something like this.
First and foremost, you assume that the Sitecore API is guaranteed to work - i.e. it's a framework - and you don't unit test it. You should be unit testing your interactions with it.
Then, download MOQ and read the quick start on how to use it. This is my preferred mocking framework. Feel free to use other frameworks if you wish.
Hopefully, Sitecore API provides a way for you to create data objects without dealing with persistence - i.e. to simply create a new instance of whatever it is you are interested in. Here is my imaginary API:
public class Post {
public string Body {get;set;}
public DateTime LastModified {get;set;}
public string Title {get;set;}
}
public interface ISiteCorePosts {
public IEnumerable<Post> GetPostsByUser(int userId);
}
In this case unit testing should be fairly easy. With a bit of Dependency Injection, you can inject the SiteCore interfaces into your component and then unit test it.
public class MyPostProcessor {
private readonly ISiteCorePosts m_postRepository;
public MyPostProcessor(ISiteCorePosts postRepository) {
m_postRepository = postRepository;
}
public void ProcessPosts(int userId) {
var posts = m_postRepository.GetPostsByUser(userId);
//do something with posts
}
}
public class MyPostProcessorTest {
[TestMethod]
ProcessPostsShouldCallGetPostsByUser() {
var siteCorePostsMock = new Mock<ISiteCorePosts>();
//Sets up the mock to return a list of posts when called with userId = 5
siteCorePostsMock.Setup(m=>m.GetPostsByUser(5)).Returns(new List<Post>{/*fake posts*/});
MyPostProcessor target = new MyPostProcessor(siteCorePostsMock.Object);
target.ProcessPosts(5);
//Verifies that all setups are called
siteCorePostsMock.VerifyAll();
}
}
If ISiteCorePosts is not, in fact, an interface and is a concrete class whose methods are not virtual and thus cannot be mocked, you will need to use Facade pattern to wrap the SiteCore interaction to make it more testing friendly.
public class SiteCorePostsFacade {
SiteCorePosts m_Posts = new SiteCorePosts();
//important - make this method virtual so it can be mocked without needing an interface
public virtual IEnumerable<Post> GetPostsByUser(int userId) {
return m_Posts.GetPostsByUser(userId);
}
}
You then proceed to use SiteCorePostsFacade as though it was an interface in the previous example. Good thing about MOQ is that it allows you to mock concrete classes with virtual methods, not just interfaces.
With this approach, you should be able to inject all sorts of data into your application to test all interactions with SiteCore API.
we have used a custom WebControl placed on a WebForm for our integration tests some years now, which wraps the NUnit Test Suite runner functionality much like the NUnit GUI. It show a pretty grid of executed tests with links to fixtures and categories to execute specific tests. Its created much like described here http://adeneys.wordpress.com/2010/04/13/new-technique-for-unit-testing-renderings-in-sitecore/ (the custom test runner part). Our implementation can also return raw NUnit xml for further processing by for example a build server.
I've tried MSTest a while back and it also works when specified that it should launch a WebDev / IIS site to test. It works but is extremely slow compared to above solution.
Happy testing!
Short answer:
You need to mock calls to SiteCore CMS.
Long answer:
I am not aware about SiteCore CMS. But, from your question looks like it is something that is external to your application. Components external to your system should always be used via interface. This has two benefits:
If you want to use another CMS system, you can easily do as your application is just talking to an interface.
It helps you with behavior testing by mocking the interface.
The code you write is your responsibility and hence you should only unit test that piece of code. Your unit tests should ensure that your code calls appropriate SiteCode CMS methods in various scenarios (behavior tests). You can do this using mocking. I use moq for mocking.
As tugga said, it depends upon how tightly the code you want to test is coupled to SiteCore. If it's something like:
SomeSiteCoreService siteCoreDependency = new SomeSiteCoreService()
Then this would be very difficult to test. If SiteCore provides you an interface, then you have more flexibility to unit test it. You could pass the implementation into your method either (contstructor, class property, or method parameter) and then you can send in a fake implementation of that service.
If they do not provide you with an interface, then you have to do a little more work. You would write an adapter interface of your own and the default implementation would delegate to the 3rd party dependency.
public interface ICMSAdapter{
void DoSomethingWithCMS()
}
public class SiteCoreCMSAdapter: ICMSAdapter{
SiteCoreService _cms = new SiteCoreService();
public void DoSomethingWithCMS(){
_cms.DoSomething();
}
That keeps your 3rd party dependencies at arms length and provides seams to all sorts of cool things, like unit tests and you do interception style architecture and do your own thing before and after the call.
}
I was able to get unit tests to interact with sitecore api in VS 2015. The same test throws a StackOverflow exception when run in VS 2012.
For example, this method call runs fine in VS2015 but not VS2015:
Context.SetActiveSite("mysite");
quick note: this assumes you have a site named mysite setup in your config file