Grails unit test cases are not working after upgrading from 1.3.7 to 2.4.4 - unit-testing

I have migrated Grails from 1.3.7 to version 2.4.4. And now when I run unit test cases it fails with below reason. There are 45 plus test cases which fail with below exception:
Tests in error:
testEdit(AddressControllerTest): No signature of method: static entity.Address.get() is applicable for argument types: (null) values: [null]
My class name is AddressController.groovy
def edit = {
def quoteInstance = Quote.get( params.id )
if(!quoteInstance) {
flash.message = "Quote not found with id ${params.id}"
redirect(action:list)
}
else {
return [ quoteInstance : quoteInstance ]
}
}
And this is the before method:
#Before
public void setUp() {
super.setUp()
flash = [ : ]
AddressController.metaClass.getFlash= { -> flash }
params = [ : ]
AddressController.metaClass.getParams = { -> params }
redirectParams = [ : ]
AddressController.metaClass.'static'.redirect = { Map args ->
redirectParams = args }
renderParams= [ : ]
AddressController.metaClass.render = { Map args -> renderParams = args }
}
And the actual test case is:
#Test
public void testEdit(){
params['id'] = 123 ;
Quote.metaClass.static.get = { int id ->
assertEquals params.id, id
return null
}
QuoteController cc = new QuoteController()
cc.edit()
assertEquals 'Quote not found with id 123', flash.message
assertEquals cc.list, redirectParams.action
}
I suspect the GUnit jar class might have been change.

Related

Ktor - Unit testing is throwing 404

I have a simple program in Ktor. It runs perfectly, but when I run the unit testing class it only throws this error: "expected:<200 OK> but was:<404 Not Found>"
This is my unit test code:
class ApplicationTest {
#Test
fun testRoot() = testApplication {
val response = client.get("/")
assertEquals(HttpStatusCode.OK, response.status)
}
#Test
fun testStart() = testApplication {
val response = client.post("/start")
assertEquals(HttpStatusCode.OK, response.status)
}
}
This is my Application.kt:
const val enableHTTPS = false
const val portHTTP = 80
const val portHTTPS = 7001
lateinit var environment: ApplicationEngineEnvironment
fun main() {
initEnvironment()
embeddedServer(Netty, environment = environment).start(wait = true)
}
My routing file is:
fun Application.configureRouting() {
routing {
get {
call.respond(ApiDetails())
}
post("/start") {
call.response.status(HttpStatusCode.OK)
}
post("/move") {
val gameDetails: GameDetails = call.receive()
val move = BasicStrategy().move(gameDetails, application)
call.respond(move)
}
post("/end") {
}
}
}
To test an application, its modules should be loaded to testApplication. Loading modules to testApplication depends on the way used to create a server: by using the application.conf configuration file or in code using the embeddedServer function.
If you have the application.conf file in the resources folder, testApplication loads all modules and properties specified in the configuration file automatically.
You can disable loading modules by customizing an environment for tests.
If you use embeddedServer, you can add modules to a test application manually using the application function:
fun testModule1() = testApplication {
application {
module1()
module2()
}
}
In your case:
class ApplicationTest {
#Test
fun testRoot() = testApplication {
application {
configureRouting()
}
environment {
config = MapApplicationConfig(
"ktor.deployment.port" to "80",
"ktor.deployment.sslPort" to "7001"
)
}
val response = client.get("/")
assertEquals(HttpStatusCode.OK, response.status)
}
#Test
fun testStart() = testApplication {
application {
configureRouting()
}
environment {
config = MapApplicationConfig(
"ktor.deployment.port" to "80",
"ktor.deployment.sslPort" to "7001"
)
}
val response = client.post("/start")
assertEquals(HttpStatusCode.OK, response.status)
}
}

Jacoco doesnt report coverage correctly

I'm trying to set up jacoco for an android project, but there are two issues with the generated report.
1- I declared the destination folder for HTML and XML report but the generated report appears in build/reports/coverage/androidTest/debug
2- the generated report is incorrect and shows that the adder class is not covered, which is wrong.
adder class
class Adder {
fun adder(a:Int,b:Int):Int{
return a+b
}
fun subtractor(a:Int,b:Int):Int{
return a-b
}
}
test class
class AdderTest {
#Test
fun `test`(){
assertEquals(3,Adder().adder(1,2))
}
#Test
fun `substract`(){
assertEquals(-1,Adder().subtractor(1,2))
}
}
jacoco script
apply plugin: 'jacoco'
project.afterEvaluate { project ->
setupAndroidReporting()
}
def setupAndroidReporting() {
tasks.withType(Test) {
// Whether or not classes without source location should be instrumented
jacoco.includeNoLocationClasses = true
jacoco.excludes = ['jdk.internal.*']
}
// Grab all build types and product flavors
def buildTypes = android.buildTypes.collect { type ->
type.name
}
def productFlavors = android.productFlavors.collect { flavor ->
flavor.name
}
// When no product flavors defined, use empty
if (!productFlavors) productFlavors.add('')
productFlavors.each { productFlavorName ->
buildTypes.each { buildTypeName ->
def sourceName, sourcePath
if (!productFlavorName) {
sourceName = sourcePath = "${buildTypeName}"
} else {
sourceName = "${productFlavorName}${buildTypeName.capitalize()}"
sourcePath = "${productFlavorName}/${buildTypeName}"
}
def testTaskName = "test${sourceName.capitalize()}UnitTest"
System.out.println("Task -> $testTaskName")
// Create coverage task of form 'testFlavorTypeCoverage' depending on 'testFlavorTypeUnitTest'
task "${testTaskName}Coverage1"(type: JacocoReport, dependsOn: "$testTaskName") {
group = "Reporting"
description = "Generate Jacoco coverage reports on the ${sourceName.capitalize()} build."
if (buildTypeName == 'debug') {
reports {
csv.enabled true // change if needed
xml.enabled false // change if needed
xml.setDestination(new File("${project.rootDir.path}/coverage-report"))
html {
enabled true
destination new File("${project.rootDir.path}/coverage-report")
}
}
def fileFilter = [
]
def javaTree = fileTree(dir: "${project.buildDir}/intermediates/javac/$sourceName/classes", excludes: fileFilter)
def kotlinTree = fileTree(dir: "${project.buildDir}/tmp/kotlin-classes/$sourceName", excludes: fileFilter)
classDirectories.from = files([javaTree], [kotlinTree])
executionData.from = files("${project.buildDir}/jacoco/${testTaskName}.exec")
def coverageSourceDirs = ["src/main/java",
"src/$productFlavorName/java",
"src/$buildTypeName/java"]
sourceDirectories.setFrom(files(coverageSourceDirs))
additionalSourceDirs.setFrom(files(coverageSourceDirs))
println "xml report: file://${reports.xml.destination}"
println "html report: file://${reports.html.destination}/index.html"
}
}
}
}
}
android {
buildTypes {
debug {
testCoverageEnabled true
}
}
}
report

Unit Test with Nsubstitute allways return null with Lambda expression on Repository pattern

inside of the method which I'm evaluating in my Unit Test I want to return a mocked value which call my repository pattern, but always return null.
I've tried with both options below but the behavior is the same (return null):
Repository.FindAsync<User>(Arg.Is<Expression<Func<User, bool>>>(x => x.Email == "Test")).Returns(new User() { FirstName = "Test"});
and
Repository.FindAsync<User>(x => x.Email == "Test").Returns(new User() { FirstName = "Test"});
I paste the whole code of my unit test
public class WhenTestingUser : WhenTesting<Customer>
{
private IRepository Repository { get; set; }
protected override void Given()
{
Repository = Fixture.Freeze<IRepository>();
Repository.Find<User>(Arg.Any<Expression<Func<User, bool>>>()).ReturnsNull();
Repository.FindAsync<User>(Arg.Is<Expression<Func<User, bool>>>(x => x.Email == "Test")).Returns(new User() { FirstName = "Test"});
}
protected override void When()
{
SystemUnderTest.UpdateUser().GetAwaiter();
}
[Test]
public void WhenCalled()
{
throw new NotImplementedException();
}
}
I'm working with AutoFixture.AutoNSubstitute, NSubstite and NUnit
The solution is:
[Test]
public void TestUnprocessedInvoicesByCatchingExpression()
{
Expression<Func<InvoiceDTO, bool>> queryUsed = null;
IList<InvoiceDTO> expectedResults = new List<InvoiceDTO>();
_invoiceRepository
.Find(i => true)
.ReturnsForAnyArgs(x =>
{
queryUsed = (Expression<Func<InvoiceDTO, bool>>)x[0];
return expectedResults;
});
Assert.That(_sut.GetUnprocessedInvoices(), Is.SameAs(expectedResults));
AssertQueryPassesFor(queryUsed, new InvoiceDTO { IsProcessed = false, IsConfirmed = true });
AssertQueryFailsFor(queryUsed, new InvoiceDTO { IsProcessed = true, IsConfirmed = true });
}
NSubstitute - Testing for a specific linq expression

Unit test All the Actions Methods in Controller in .Net core visual studio 2017

public async Task<IActionResult> Create(DonorViewModel be, IFormFile pic)
{
be.RegCampId = Convert.ToInt32(TempData["Camp"]);
if (ModelState.IsValid)
{
DONOR entity = new DONOR();
#region Insert Entities
entity.Address = be.Address;
entity.BarCode = be.BarCode;
entity.BloodGroupId = be.BloodGroupId;
entity.CityId = be.CityId;
entity.CNIC = be.CNIC;
entity.DOB = be.DOB;
entity.Email = be.Email;
entity.EmergencyContact = be.EmergencyContact;
entity.FullName = be.FullName;
entity.GenderId = be.GenderId;
entity.HomeNo = be.HomeNo;
entity.IsActive = true;
entity.IsDeleted = false;
entity.LastDonDate = be.LastDonDate;
entity.MaritalStatus = be.MaritalStatus;
entity.MobileNo = be.MobileNo;
entity.Occupation = be.Occupation;
entity.PreDonCount = be.PreDonCount;
if (be.RegCampId != 0) { entity.RegCampId = be.RegCampId; entity.RegistrationTypeId = 3; }
if (be.RegLocId != 0) { entity.RegLocId = be.RegLocId; entity.RegistrationTypeId = 2; }
entity.SignPic = entity.SignPic;
entity.WhatsApp = be.WhatsApp;
entity.CreatedBy = (int)HttpContext.Session.GetInt32("UserId");
entity.CreatedDateTime = DateTime.Now;
#endregion
flag = await _donorContext.AddAsync(entity);
if (pic == null || pic.Length <= 0)
be.Pic = Path.Combine(_hostingEnvironment.WebRootPath, "images", "Avatar.png").Replace(_hostingEnvironment.WebRootPath, "").Replace("\\", "/");
if (pic != null && pic.Length > 0)
{
var path = Path.Combine(new string[]
{
_hostingEnvironment.WebRootPath,
"Reservoir","Donor",entity.Id.ToString(),
entity.Id + Path.GetExtension(pic.FileName)
});
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
pic.CopyTo(stream);
}
path = path.Replace(_hostingEnvironment.WebRootPath, "").Replace("\\", "/");
entity.Pic = path;
entity.CreatedBy = entity.CreatedBy;
entity.CreatedDateTime = entity.CreatedDateTime;
entity.IsActive = true;
entity.IsDeleted = false;
await _donorContext.UpdateAsync(entity);
}
if (flag)
{
TempData["Message"] = "Donor is Added Successfully.";
if (be.RegCampId != 0)
{
return RedirectToAction("Create", "Donor", new { CampId = be.RegCampId });
}
else
{
return RedirectToAction("Create", "Donor");
}
}
}
ViewData["RegCampId"] = new SelectList(_context.BLOOD_CAMP, "Id", "City", be.RegCampId);
ViewData["BloodGroupId"] = new SelectList(_bloodGroupContext.GetAll(), "Id", "Value", be.BloodGroupId);
ViewData["CityId"] = new SelectList(_cityContext.GetAll(), "Id", "Name", be.CityId);
ViewData["ScreenedBy"] = new SelectList(_context.EMPLOYEE, "Id", "FirstName", be.ScreenedBy);
ViewData["GenderId"] = new SelectList(_genderContext.GetAll(), "Id", "Name", be.GenderId);
ViewData["RegLocId"] = new SelectList(_locationService.GetAll(), "Id", "Name",be.RegLocId);
return View(be);
}
This is My Create method In Controller How to unit test it using UnitTest.
using HMS_Presentation.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//Unit Test code .
namespace HMS_UnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
DonorController Controller = new DonorController();
ViewResult result = Controller.Create() as ViewResult;
Assert.AreEqual("",????);
}
}
}
This is my unit test class code how to use my controller object to check the actions and test it . WHAT should i write the in the assert . I SEARCH it on internet but do not find any proper solution kindly check the code below and tell me what should i have to write in the assert . i am using visual studio 2017 and .NET CORE 2.0 AND adding a project of unit test in my solution.
The link i followed .
https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2017
In ASPNET Core 2.1 introduced feature called Functional testing of MVC applications.
To help streamline in-memory end-to-end testing of MVC applications using TestServer.
See below example
using Xunit;
namespace TestingMvc.Tests
{
public class TestingMvcFunctionalTests : IClassFixture<WebApplicationTestFixture<Startup>>
{
public TestingMvcFunctionalTests(WebApplicationTestFixture<Startup> fixture)
{
Client = fixture.CreateClient();
}
public HttpClient Client { get; }
[Fact]
public async Task GetHomePage()
{
// Arrange & Act
var response = await Client.GetAsync("/");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Read more about functional testing of MVC Applications click here

Upgrading Spock unit tests from Grails 1.3.9 to Grails 2.3.9. But edit() test is failing

I am updating unit tests in a Grails project. We were originally using version 1.3.9 and now we are updating to version 2.3.9. I am using Spock.
I keep getting this error:
results:
junit.framework.AssertionFailedError: Condition not satisfied:
controller.edit() == [filterCategoryInstance: filterCategoryInstance]
| | | |
| null false John
com.xxxxxx.xxxxx.FilterCategoryController#20574000
Here is the controller code:
#Secured(["hasAnyRole('CM_ADMIN')"])
def edit() {
def filterCategoryInstance = FilterCategory.get(params.id)
if (!filterCategoryInstance) {
flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'dpFilterCategory.label', default: 'FilterCategory'), params.id])}"
redirect(action: "list")
}
else {
return [filterCategoryInstance: filterCategoryInstance]
}
}
and here is the test code:
#Mock([FilterCategory, FilterCategoryTag])
#TestFor(FilterCategoryController)
#TestMixin(DomainClassUnitTestMixin)
class FilterCategoryControllerSpec extends ExtendedControllerSpec {
def 'edit action: existing FilterCategory'() {
setup:
mockI18N(FilterCategoryController)
params.id = filterCategoryInstance.id
expect:
controller.edit() == [filterCategoryInstance: filterCategoryInstance]
where:
tag = new FilterCategoryTag(name: 'tag1')
filterCategoryInstance = new FilterCategory(name: "John",
submissionText:"John", sortOrder:0, 'filterCategoryTags': [tag])
}
And here is the ExtendedControllerSpec code. I hope I have included enough code:
I have looked at the following web pages for guidance:
#Mixin(MetaClassMixin)
class ExtendedControllerSpec extends Specification {
def props
protected void setup() {
//super.setup()
props = new Properties()
File file = new File("grails-app/i18n/messages.properties")
if (file.exists()) {
def stream = new FileInputStream(file)
props.load stream
stream.close()
}
mockI18N(controller)
}
def mockI18N = { controller ->
controller.metaClass.message = { Map map ->
if (!map.code)
return ""
if (map.args) {
def formatter = new MessageFormat("")
if (props.getProperty(map.code)) {
formatter.applyPattern props.getProperty(map.code)
}
return formatter.format(map.args.toArray())
} else {
if (props && props.hasProperty(map.code)) {
return props.getProperty(map.code)
} else {
return map.code
}
}
}
}
/**
* add dynamic methods in test setup.
*/
protected void addDynamicMethods() {
registerMetaClass(String)
String.metaClass.mixin StringUtils
}
protected GrailsUser mockGrailsUser() {
return Mock(GrailsUser)
}
...
/**
* must call AFTER mockDpSercurityService
*/
protected void setHasRoleTrue() {
if (controller?.dpSecurityService?.metaClass) {
controller.dpSecurityService.metaClass.hasRole = {return true}
}
}
protected void setHasRoleFalse() {
if (controller?.dpSecurityService?.metaClass) {
controller.dpSecurityService.metaClass.hasRole = {return false}
}
}
protected void mockUserService() {
controller.dpUserService = new MockFor(UserService)
}
}
http://sanjaykanwar.blogspot.com/2012/07/grails-controller-test-with-spock.html
http://naleid.com/blog/2012/05/01/upgrading-to-grails-2-unit-testing
Looks like the if branch gets executed in edit() instead of the else branch because FilterCategory does not get saved and therfore does not get a proper id.